zoukankan      html  css  js  c++  java
  • 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; } } };
  • 相关阅读:
    viewpager切换时底下的背景图标动画切换
    hdu 1594水题
    hdu 4256大水题
    hdu 1856并查集
    hdu4247水题
    hdu 4252单调栈
    hdu 4248排列问题
    hdu 1210
    hdu4245
    hdu 1593找规律题
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3834041.html
Copyright © 2011-2022 走看看