• 平衡二叉树判断方法简介


    判断该树是不是平衡的二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
    方法一:先序遍历

    1.计算节点深度

    private int height(BinaryNode root){
        if(root == null)
            return 0;
        int left_height = height(root.left);
        int right_height = height(root.right);
        return 1 + (left_height > right_height ? left_height : right_height);
    }

    2.递归判断是否平衡

    public boolean isBalanced(binarytreenode root){
        if(root ==null)
            return true;
        int left = height(root.leftnode);
        int right = height(root.rightnode);
        int diff = left - right;
        if(diff > 1 || diff <-1)
            return false;
        return isBalanced(root.leftnode) && isBalanced(root.rightnode);
    }

    上面的“先序遍历”判断二叉树平衡的方法,时间复杂度比较大。因为,二叉树中的很多结点遍历了多次。

    方法二:后序遍历

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            int depth;
            return IsBalanced(pRoot,&depth);
        }
     
        bool IsBalanced(TreeNode* pRoot,int*pDepth){
            if(pRoot==NULL){
                *pDepth=0;
                return true;
            }
     
            int leftdepth,rightdepth; //在递归中声明临时变量,用于求父节点传来的指针对应的值。
            if(IsBalanced(pRoot->left,&leftdepth)&&IsBalanced(pRoot->right,&rightdepth)){
                if(abs(leftdepth-rightdepth)<=1){
                    *pDepth=leftdepth>rightdepth?leftdepth+1:rightdepth+1;
                    return true;
                }
            }
            return false;
        }
    }

     

  • 相关阅读:
    高斯核函数的代码体现
    程序编译
    DoH
    随笔1
    获取节点值的方式
    DOM解析XML
    URLConnection发送请求,并接收数据
    myeclipse编译后的jsp文件存放位置
    各种中文乱码
    各种提交的区别
  • 原文地址:https://www.cnblogs.com/atai/p/9665417.html
Copyright © 2020-2023  润新知