LeetCode | Balanced Binary Tree

来源:互联网 发布:淘宝网店交易 编辑:程序博客网 时间:2024/06/04 18:29

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.

判断平衡二叉树,常规的写法是两个递归,一个递归用于计算所有节点,另一个递归用于计算每一个节点的深度。

新的方法是直接使用递归计算深度,但是在计算深度之前需要判断左右子树的深度之差是否大于1,如果是,说明不符合要求,以-1标记。递归下来的时候,只要计算到left、right或者当前的abs(left-right)>1的时候就表明子树或者自己本身不符合平衡二叉树,递归返回。

class Solution {public:    bool isBalanced(TreeNode* root) {        return isBalancedTree(root) >=0;    }    int isBalancedTree(TreeNode* root){        if(!root) return 0;        int left=isBalancedTree(root->left);        int right=isBalancedTree(root->right);        //判断不符合,提前退出        //类似if(abs(left-right)>1) return false;这句        //也就是这个条件不符合就return false        //符合这个条件了,还需要继续判断后面的        if(left<0 || right<0 || abs(left-right)>1) return -1;        return left>right?(left+1):(right+1);    }    // bool isBalanced(TreeNode* root) {    //     if(root==NULL) return true;    //     //只有一个bool,深度如何可以传递    //     //事实证明需要另开一个函数    //     int left=getDepth(root->left);    //     int right=getDepth(root->right);    //     if(abs(left-right)>1) return false;    //     //于是这种还是利用了双循环    //     return isBalanced(root->left) && isBalanced(root->right);    // }    // int getDepth(TreeNode* root){    //     int depth=0;    //     if(root){    //         int left=getDepth(root->left);    //         int right=getDepth(root->right);    //         return left>right?(left+1):(right+1);    //     }    //     return depth;    // }};
0 0
原创粉丝点击