zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Count Complete Tree Nodes

    Count Complete Tree Nodes

    Given a complete binary tree, count the number of nodes.

    Definition of a complete binary tree from Wikipedia:
    In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

    https://leetcode.com/problems/count-complete-tree-nodes/


    Tricky的做法,往左找到最深的叶子节点,往右再找最深的叶子节点。

    如果他们的深度一样,说明是棵完全二叉树,节点数套用公式2^n - 1。

    否则再用同样的方法递归这个点的左子树和右子树。

    犯2把循环条件写成了while(leftChild && leftChild.val),val可能是0,结果就不对了ORZ。

     1 /**
     2  * Definition for a binary tree node.
     3  * function TreeNode(val) {
     4  *     this.val = val;
     5  *     this.left = this.right = null;
     6  * }
     7  */
     8 /**
     9  * @param {TreeNode} root
    10  * @return {number}
    11  */
    12 var countNodes = function(root) {
    13     return treeNodes(root);
    14 
    15     function treeNodes(node){
    16         if(!node){
    17             return 0;
    18         }else{
    19             var leftDepth = 0;
    20             var rightDepth = 0;
    21             var leftChild = node.left;
    22             while(leftChild){
    23                 leftDepth++;
    24                 leftChild = leftChild.left;
    25             }
    26             var rightChild = node.right;
    27             while(rightChild){
    28                 rightDepth++;
    29                 rightChild = rightChild.right;
    30             }
    31             if(leftDepth === rightDepth){
    32                 return Math.pow(2, leftDepth + 1) - 1;
    33             }else{
    34                 return treeNodes(node.left) + treeNodes(node.right) + 1;
    35             }
    36         }
    37     }
    38 };
  • 相关阅读:
    Git 安装部署的详细说明
    jmeter数据库连接异常记录
    安装测试真的有那么简单吗?
    5G通信系统简单介绍
    postman 模拟服务器server
    再来对http协议做个详细认识
    关于Fiddler Everywhere的使用说明
    pom模式+ddt思想+logger+allure 重构jpress
    adb常见异常归类
    DDT思想
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4558221.html
Copyright © 2011-2022 走看看