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; } } };
  • 相关阅读:
    深入Python(一)
    深入Python(二)
    初识Python(五)
    初识Python(一)
    深入Python(三)
    一、MongoDB的下载、安装与部署
    浏览器上的javascript
    javascript中的事件
    扩展方法
    团队项目开题报告
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3834041.html
Copyright © 2011-2022 走看看