zoukankan      html  css  js  c++  java
  • 12.判断一棵二叉树是否是平衡二叉树(JavaScript版)

    判断一棵二叉树是否是平衡二叉树:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script>
            //二叉平衡搜索树:
            //1.根节点的左子树与右子树的高度差不能超过1
            //2.这棵二叉树的每个子树都符合第一条
    
            function Node(value){
                this.value = value;
                this.left = null;
                this.right = null;
            }
    
            var nodeA = new Node("a");
            var nodeB = new Node("b");
            var nodeC = new Node("c");
            var nodeD = new Node("d");
            var nodeE = new Node("e");
            var nodeF = new Node("f");
            var nodeG = new Node("g");
    
            nodeA.left = nodeB;
            nodeA.right = nodeC;
            nodeB.left = nodeD;
            nodeB.right = nodeE;
            nodeC.left = nodeF;
            nodeC.right = nodeG;
    
            //判断二叉树是否平衡
            function isBalance(root){
                if(root == null) return true;
                //获取左右的深度
                var leftDeep = getDeep(root.left);
                var rightDeep = getDeep(root.right);
                //若左右深度相差大于1,则不是平衡树
                if(Math.abs(leftDeep - rightDeep) > 1){
                    return false;
                }else{
                    //判断左右子树是否平衡
                    return isBalance(root.left) && isBalance(root.right);
                }
            }
    
            //获取树的深度
            function getDeep(root){
                if(root == null) return 0;
                var leftDeep = getDeep(root.left);
                var rightDeep = getDeep(root.right);
                return Math.max(leftDeep, rightDeep) + 1;//取两个深度中最大的一个,加上自身
            }
    
            console.log(isBalance(nodeA));
        </script>
    </body>
    </html>
    判断平衡二叉树
  • 相关阅读:
    hdu2476 string painter
    lightoj1422 Halloween Costumes
    cf1369D---找规律,递推
    cf1368D---贪心
    cf1373D---思维,最大子段和
    poj2279 Mr. Young's Picture Permutations
    AT2442 fohen phenomenon 差分
    poj2796 feel good 单调栈
    poj2082 terrible sets 单调栈
    洛谷P2979 cheese towers
  • 原文地址:https://www.cnblogs.com/lanshanxiao/p/13198769.html
Copyright © 2011-2022 走看看