LeetCode OJ-- Balanced Binary Tree ***

https://oj.leetcode.com/problems/balanced-binary-tree/

判断一个二叉树,是否为平衡的。如果是平衡的,则它的每个子树的左右子树高度差不大于1.

递归

但是有两个值,在高层都需要知道。一个是子树是否为二叉树的 bool,一个是子树的高度。所以,一个作为返回值,一个作为引用给传到上面来。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if(root == NULL)
            return true;
        int p;
        return getDepth(root,p);
    }
 
    bool getDepth(TreeNode *root, int &depth)
    {
        if(root == NULL)
        {
            depth = 0;
            return true;
        }
            
        if(root->left == NULL && root->right == NULL)
        {
            depth = 1;
            return true;
        }
        
        int l, r;
        if(getDepth(root->left, l) == false)
            return false;
        if(getDepth(root->right, r) == false)
            return false;
        
        if(abs(l-r)>1)
            return false;
        else
        {
//此时,depth需要传到上层去 depth
= max(l,r) + 1; return true; } } };
原文地址:https://www.cnblogs.com/qingcheng/p/3834041.html