leetcode之Balanced Binary Tree

来源:互联网 发布:淘宝上的众筹是真的吗 编辑:程序博客网 时间:2024/06/07 20:52

采用递归思想,递归的结束条件尤其要注意。当左右子树的深度之差的绝对值>1,就一定不是平衡二叉树。注意的是,讲条件反过来说,左右子树的深度之差绝对值<=1,也不一定是平衡二叉树!!这一点要绝对注意!!

(1)C++实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 int depth(TreeNode* p){
     if(p == NULL)
        return 0;
    return 1+max(depth(p->left),depth(p->right));
 }
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root == NULL)
            return true;
        if(root->left == NULL && root->right == NULL)
            return true;
        if(abs(depth(root->left)-depth(root->right))>1)
            return false;
        return isBalanced(root->left)&&isBalanced(root->right);
    }
};

(2)java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        if(root.left == null && root.right == null)
            return true;
        if(Math.abs(depth(root.left)-depth(root.right))>1)
            return false;
        return isBalanced(root.left)&&isBalanced(root.right);
        }
                
        public int depth(TreeNode tr){
            if(tr == null)
                return 0;
            return 1+Math.max(depth(tr.left), depth(tr.right));
    }
}

0 0
原创粉丝点击