zoukankan      html  css  js  c++  java
  • 110. Balanced Binary Tree

    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.

    判断二叉树是不是平衡二叉树

    递归求左右子树的高度差,为了效率,在判断的过程中记录下子树的深度。

    当左右子树都平衡时,再判断高度差。

    代码如下:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isBalance(TreeNode* root, int &dep) {
            if (root == NULL) {
                dep = 0;
                return true;
            }
            int l ,r;
            int left = 0,right = 0;
            l = isBalance(root->left,left);
            r = isBalance(root->right,right);
            if (l && r) {
                dep = max(left, right) + 1;
                if (abs(left - right) <= 1) return true;
                return false;
            }
            else return false;
        }
        bool isBalanced(TreeNode* root) {
            int dep = 0;
            if (root == NULL) return true;
            if (isBalance(root, dep)) return true;
            return false;
        }
    };
  • 相关阅读:
    Apache-Shiro
    Linux下的Nginx安装
    Linux安装Redis
    Linux安装ftp组件vsftpd
    Spring笔记(二)
    Spring笔记(一)
    MySQL事务
    rocketMQ基本理解
    2018面试题小结
    v-if和v-show
  • 原文地址:https://www.cnblogs.com/pk28/p/7227726.html
Copyright © 2011-2022 走看看