zoukankan      html  css  js  c++  java
  • 剑指offer系列——39.平衡二叉树

    Q:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
    A:
    结合上一题的计算树的高度。

        bool IsBalanced_Solution(TreeNode *pRoot) {
            vector<int> diff = {-1, 0, 1};
            if (pRoot == nullptr)
                return true;
            int l = TreeDepth(pRoot->left);
            int r = TreeDepth(pRoot->right);
            int d = l - r;
            vector<int>::iterator it;
            it = find(diff.begin(), diff.end(), d);
            if (it == diff.end())
                return false;
            else {
                bool left = IsBalanced_Solution(pRoot->left);
                bool right = IsBalanced_Solution(pRoot->right);
                return left && right;
            }
        }
    
        int TreeDepth(TreeNode *pRoot) {
            if (pRoot == nullptr)
                return 0;
            int l = TreeDepth(pRoot->left);
            int r = TreeDepth(pRoot->right);
            return l > r ? l + 1 : r + 1;
        }
    

    但这样做有一个问题,就是下层一直累积遍历很多次。这样直接在遍历过程中进行判断。

        bool IsBalanced(TreeNode *root, int & dep){
            if(root == NULL){
                return true;
            }
            int left = 0;
            int right = 0;
            if(IsBalanced(root->left,left) && IsBalanced(root->right, right)){
                int dif = left - right;
                if(dif<-1 || dif >1)
                    return false;
                dep = (left > right ? left : right) + 1;
                return true;
            }
            return false;
        }
        bool IsBalanced_Solution(TreeNode* pRoot) {
            int dep = 0;
            return IsBalanced(pRoot, dep);
        }
    
  • 相关阅读:
    ubuntu18 升级cmake
    开源镜像站汇总
    ubuntu18安装go
    tendermint框架及Tx执行流程
    常用python内置函数
    根据列号返回列名
    Valid Number
    Remove Duplicates from Sorted List II
    vector排序问题<unresolved overloaded function type>
    Spiral Matrix
  • 原文地址:https://www.cnblogs.com/xym4869/p/12326883.html
Copyright © 2011-2022 走看看