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>
    判断平衡二叉树
  • 相关阅读:
    代码对齐--string|stream
    pytest_30_40
    性能总结
    day41_IO模型
    postman_05_cookie_case_流(顺序)
    linux_压缩
    post_04_assert_请求参数预处理_pre_requests
    postman_网址
    postman_03_引用随机变量($guid,$timestamp,$randomInt)_and_参数引用外部文件
    CF 1354C2 思维
  • 原文地址:https://www.cnblogs.com/lanshanxiao/p/13198769.html
Copyright © 2011-2022 走看看