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);
        }
    
  • 相关阅读:
    javascript学习一
    对软件工程课程的认识
    人月神话读后感
    项目开发总结报告(GB8567——88)
    MFC双缓冲绘图
    QT连接MySQL
    [QT学习]拷贝文件
    Arduino入门笔记【1】
    《人月神话》读后感以及软件工程总结
    十天冲刺任务(第二次冲刺)
  • 原文地址:https://www.cnblogs.com/xym4869/p/12326883.html
Copyright © 2011-2022 走看看