• 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.

    解法一:根据题意有一种解法,即直接递归访问整颗树,计算每个节点两棵子树的高度。但效率不高,这代码会递归访问每个结点的整棵子树,也就是说getHeight函数会反复调用计算同一个结点的高度。算法复杂度为O(NlogN);

    /**
     * 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 getHeight(TreeNode *root) {
            if(root == NULL) return 0;
            return max(getHeight(root->left),getHeight(root->right)) +1 ;
        }
        bool isBalanced(TreeNode *root) {
            if(root == NULL)
                return false;
            int heightDiff = getHeight(root->left) - getHeight(root->right);
            if(abs(heightDiff) > 1) 
                return false;
            else
                return isBalanced(root->left) && isBalanced(root->right);
        }
    };    

    解法二:根据解法一思路,我们可以删减部分getHeight的调用,仔细查看getHeight函数,你会发现getHeight不仅可以检查高度,还能检查这棵树是否平衡。那么我们发现子树不平衡时直接返回-1不就可以了嘛。

    改进后的算法会从根结点递归检测每棵子树的高度。通过checkHeight方法,以递归方式获取每个结点左右子树的高度,若子树平衡,则返回该子树的实际高度。若子树不平衡,则返回-1。代码复杂度:O(N)时间和O(H)的空间,其中H为树的高度。

    /**
     * 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 checkHeight(TreeNode *root) {
            if(root == NULL) return 0;
            
            int leftHeight = checkHeight(root->left);
            if(leftHeight == -1) return -1;
            
            int rightHeight = checkHeight(root->right);
            if(rightHeight == -1) return -1;
            
            int heightDiff = leftHeight - rightHeight;
            if(abs(heightDiff) > 1) return -1;
            else return max(leftHeight,rightHeight)+1;
        }
        bool isBalanced(TreeNode *root) {
            if(checkHeight(root) == -1)
                return false;
            else
                return true;
        }
    };
  • 相关阅读:
    Qt 定时器事件startTimer
    认识网络、几种常用的网络拓扑图
    拓扑结构图,什么是拓扑结构
    Qt 利用QTime类来控制时间,QTime的成员函数的用法
    Qt QTime类的使用
    Qt 打开文件的默认路径 QFileDialog::getOpenFileName()
    Qt QWidget颜色设置的三种方法
    Qt 多个QDockWidget 切换显示
    Qt QString 格式化 arg 前面自动补0
    Qt 使用QMediaPlayer报错 defaultServiceProvider::requestService(): no service found for
  • 原文地址:https://www.cnblogs.com/chenbjin/p/3703569.html
Copyright © 2020-2023  润新知