Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断是不是平衡树,本来的想法是复用求树的高度的那个函数,但是那样的话,其实相当于DFS了树两次,时间浪费。如这样
- bool isBalanced(TreeNode *root) {
- if(root==NULL)
- return true;
- int leftheight=maxHeight(root->left);
- int rightheight=maxHeight(root->right);
- return isBalanced(root->left) && isBalanced(root->right) &&(leftheight-rightheight<2 && leftheight-rightheight>-2);
- }
- int maxHeight(TreeNode * root){
- if(root==NULL)
- return 0;
- return 1+std::max(maxHeight(root->left),maxHeight(root->right));
- }
这题最大的亮点是如何在一次递归中返回两个数。可以用返回值返回一个,另一个可以是传一个引用或者全局变量。
- int height(TreeNode *root, bool & result){
- if(root==NULL || result==false)
- return 0;
- int l=height(root->left, result);
- int r=height(root->right, result);
- if(abs(l-r)>1)
- result=false;
- return max(l,r)+1;
- }
-
- bool isBalanced(TreeNode *root) {
- bool result=true;
- height(root,result);
- return result;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议