zoukankan      html  css  js  c++  java
  • 平衡二叉树

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    解题思路:
    这里所说的平衡二叉树不要求是搜索树,平常意义上的二叉平衡树一般都是指平衡二叉搜索树。
    那么只需要判断任何一个节点的左右子树高度差是否大于1即可。
     
    class Solution {
    public:
        bool isBalanTree = true;
        int travalTree(TreeNode* root, int depth){
            if(root == NULL){
                return depth;
            }
            if(root->left == NULL && root->right == NULL){
                return depth;
            }
            int lh = depth;
            if(root->left != NULL){
                lh = travalTree(root->left, depth+1);
            }
            int rh = depth;
            if(root->right != NULL){
                 rh = travalTree(root->right, depth+1);
            }
           // cout<< "lh="<<lh<< " rh=" <<rh<<endl;
            if((lh == depth && rh - depth > 1) || (rh == depth && lh - depth > 1) || abs(lh-rh) >1){
                isBalanTree = false;
            }
            return max(lh, rh);
        }
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot == NULL) return true;
    
            travalTree(pRoot, 1);
    
            return isBalanTree;
        }
    };
    

      

  • 相关阅读:
    第四阶段学习总结
    第三阶段学习总结
    第二阶段学习总结
    第一阶段内容的学习总结
    第四单元及OO课程总结
    关于工具的碎碎念
    第三单元博客总结
    第二单元博客总结
    第一单元作业总结
    实验五 单元测试
  • 原文地址:https://www.cnblogs.com/chengsheng/p/10680564.html
Copyright © 2011-2022 走看看