[leetcode] 110. Balanced Binary Tree

来源:互联网 发布:c4d r16 mac安装 编辑:程序博客网 时间:2024/05/22 05:02

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 ofevery node never differ by more than 1.

这道题是判断二叉树是否是平衡二叉树,题目难度为Easy。

根据平衡二叉树的定义,只需要借助求二叉树深度的函数即可通过递归来判断二叉树是否平衡,而二叉树深度又可以通过深度优先的方法递归得到。具体代码:

class Solution {    int depth(TreeNode* n) {        if(!n) return 0;        return max(depth(n->left), depth(n->right)) + 1;    }public:    bool isBalanced(TreeNode* root) {        if(!root) return true;        return isBalanced(root->left) && isBalanced(root->right) && abs(depth(root->left)-depth(root->right))<=1;    }};
上面代码中自顶向下来求二叉树深度,在递归过程中靠下的节点会多次计算其深度。还可以通过自底向上的方法来计算深度,节点深度通过两个子节点深度来计算,这样就避免了对节点的多次遍历,每个节点只遍历一次,时间复杂度从O(nlogn)降到了O(n),具体代码:
class Solution {    int depth(TreeNode* n) {        if(!n) return 0;        int lDepth = depth(n->left);        if(lDepth == -1) return -1;        int rDepth = depth(n->right);        if(rDepth == -1) return -1;        if(abs(lDepth-rDepth) > 1) return -1;        return max(lDepth, rDepth) + 1;    }public:    bool isBalanced(TreeNode* root) {        return depth(root) != -1;    }};

0 0