zoukankan      html  css  js  c++  java
  • 110. Balanced Binary Tree (Tree; DFS)

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

     
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    class Solution {
    public:
        bool isBalanced(TreeNode *root) {
            if(!root) return true;
      
            flag = true;
            dfs(root,1);
            return flag;
            
        }
        int dfs(TreeNode* node, int depth){
            if(!flag)
            {
                return 0;
            }
            if(!node->left && !node->right)
            {
                return depth;
            }
            
            int left=depth;
            int right=depth;
            if(node->left)
            {
                left = dfs(node->left,depth+1);
            }
           
            if(node->right)
            {           
                right = dfs(node->right,depth+1);
            }
            
            if(abs(left-right)> 1)
            {
                flag = false;
            }
            return max(left,right);
        }
    private:
        bool flag;
    };
  • 相关阅读:
    开发入门
    Web开发的四个域
    JSP语法
    JSP入门
    变量的作用范围
    面向对象
    C#编译执行过程
    css3的渐变、背景、过渡、分页
    css3选择器总结
    css3基础选择器
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854376.html
Copyright © 2011-2022 走看看