zoukankan      html  css  js  c++  java
  • 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.

    思路:首先我们先熟悉平衡二叉树的定义,平衡二叉树或为空树,或为如下性质的二叉排序树:1)左右子树深度之差的绝对值不超过1;2)左右子树仍然为平衡二叉树.

          平衡因子BF=左子树深度-右子树深度.

    平衡二叉树每个结点的平衡因子只能是10-1。若其绝对值超过1,则该二叉排序树就是不平衡的。

    这道题主要就是计算左右子树各个深度,然后判断左右子树深度之差的绝对值不超过1.使用递归

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int DepthBalanced(TreeNode *root)
        {
            int pLeft,pRight;
            if(root==NULL)
                return 0;
            if(root->left==NULL)
                return DepthBalanced(root->right)+1;
            else if(root->right==NULL)
                return DepthBalanced(root->left)+1;
            else
            {
                pLeft=DepthBalanced(root->left);
                pRight=DepthBalanced(root->right);
                return (pLeft>pRight)?(pLeft+1):(pRight+1);
            }
        }
        bool isBalanced(TreeNode *root) {
            int pLeft,pRight;
            if(root==NULL)
                return true;
            pLeft=DepthBalanced(root->left);
            pRight=DepthBalanced(root->right);
            if(pLeft-pRight>=-1 && pLeft-pRight<=1)
                return isBalanced(root->left) && isBalanced(root->right);
            return false;
        }
    };

     另一种解法:原理差不多,把判断拿到另一个函数中去判断了。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int check(TreeNode *root,bool &value)
        {
            if(root==NULL)
            {
                return 0;
            }
            int pLeft=check(root->left,value);
            int pRight=check(root->right,value);
            int depth=(pLeft>pRight)?(pLeft+1):(pRight+1);
            if(pLeft-pRight<-1 || pLeft-pRight>1)
                value=false;
            return depth;
        }
        bool isBalanced(TreeNode *root) {
            bool value=true;
            check(root,value);
            return value;
        }
    };
  • 相关阅读:
    操作系统概述总结
    string类的用法总结
    stack的简单用法总结
    递归用法总结
    C语言中常见的图形打印总结
    C++中list的用法总结
    STL中find和sort的用法总结
    unity Physics/Physics2DProjectSettings中LayerCollisionMatrix的存储方式
    UnityEvent<T> 系列化
    十字相乘法
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3601400.html
Copyright © 2011-2022 走看看