用 C++ 平衡二叉查詢樹
假設我們有一個二叉查詢樹,我們必須找到一個具有相同節點值的平衡二叉查詢樹。當且僅當每個節點的兩個子樹的深度僅差 1 時,才稱二叉查詢樹為平衡的。如果有多個結果,則返回任何一個結果。如果樹像這樣:-
為了解決此問題,我們將按照以下步驟操作:-
定義 inorder() 方法,它將按順序遍歷序列儲存到陣列中
定義 construct 方法(),它將採用 low 和 high -
如果 low > high,則返回 null
mid := low + (high - low) / 2
root := 帶有值 arr[mid] 的新節點
root 的左側 := construct(low, mid – 1),root 的右側 := construct(mid + 1, high)
返回 root
從 main 方法呼叫 inorder 方法並返回 construct(0, arr - 1 的大小)
示例 (C++)
讓我們看看以下實現以更好地理解 -
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr->val == 0 || curr == NULL){ cout << "null" << ", "; }else{ cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: vector <int> arr; void inorder(TreeNode* node){ if(!node || node->val == 0) return; inorder(node->left); arr.push_back(node->val); inorder(node->right); } TreeNode* construct(int low, int high){ if(low > high) return NULL; int mid = low + (high - low) / 2; TreeNode* root = new TreeNode(arr[mid]); root->left = construct(low, mid - 1); root->right = construct(mid + 1, high); return root; } TreeNode* balanceBST(TreeNode* root) { inorder(root); return construct(0, (int)arr.size() - 1); } }; main(){ vector<int> v = {1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4}; TreeNode *root = make_tree(v); Solution ob; tree_level_trav(ob.balanceBST(root)); }
輸入
[1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4]
輸出
[2, 1, 3, 4, ]
廣告