赞
踩
平衡树(Balance Tree,BT) 指的是,任意节点的子树的高度差都小于等于1。
常见的符合平衡树的有:
从上到下判断(DFS先序遍历)
depth 函数计算当前节点cur的深度:
isBalanced 函数实现判断:
当前子树
是不是平衡树,再判断 左右子树
是不是平衡树(先序遍历递归(根左右)
)。/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int depth(TreeNode* cur){ // 计算cur深度
if(!cur) return 0;
return max(depth(cur->right), depth(cur->left)) + 1;
}
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr) return true;
return abs(depth(root->left) - depth(root->right)) <=1 && isBalanced(root->left) && isBalanced(root->right);
}
};
从下到上判断(DFS后序遍历)
fun 函数实现后序遍历+剪枝:
cur 的左 / 右子树的深度差 ≤1
时:表明 当前子树仍为平衡树
,返回当前子树的深度,即 左 / 右子树的深度最大值 +1( max(left, right) + 1
), ;左 / 右子树的深度差 >1
时 :则返回 -1
(也可以是其他负值,主要用来标明 此子树不是平衡树
,方便后续剪枝 )。−1
:代表此树的 左(右)子树
不是平衡树,可行性剪枝,直接返回 −1
;isBalanced 函数实现判断:
fun(root) != -1
,则说明此树平衡,返回 true
; 否则返回 false
。class Solution { // 后序遍历+剪枝
int fun(TreeNode* cur){
if(!cur) return 0;
int left = fun(cur->left);
if(left==-1) return -1; // 剪枝
int right = fun(cur->right);
if(right==-1) return -1; // 剪枝
return abs(left-right) < 2 ? max(left, right) + 1 : -1;
}
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr) return true;;
return fun(root)!=-1;
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。