在 C++ 中平衡二叉搜索树
c++server side programmingprogramming
假设我们有一个二叉搜索树,我们必须找到一个具有相同节点值的平衡二叉搜索树。当且仅当每个节点的两个子树的深度相差不超过 1 时,二叉搜索树才被认为是平衡的。如果有多个结果,则返回其中任何一个。所以如果树像 −
为了解决这个问题,我们将遵循以下步骤 −
定义 inorder() 方法,这将按顺序遍历序列存储到数组中
定义构造方法(),这将取低和高 −
如果低 > high 则返回 null
mid := low + (high - low) / 2
root := new node with value arr[mid]
root 的左侧 := constrain(low, mid – 1) 且 root 的右侧 := constrain(mid + 1, high)
返回 root
从 main 方法中,调用 inorder 方法并返回 constrain(0, size of 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, ]