• LeetCode——Count Complete Tree Nodes


    Description:

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

    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.

    思路:给一颗完全二叉树求其节点的个数。首先要明确完全二叉树的定义:把满二叉树从上到下,从左到右进行编号,完全二叉树是其中编号没有断续的部分。也就是说完全二叉树只可能在最右子树的叶子节点的位子上有空缺。而且左右子树的高度差不能大于1。所以只要是count(左节点)==count(右节点)那么就是一颗满二叉树。可以用公式计算出节点的个数NodeCount=2^h - 1。若不是满二叉树的话就递归遍历求count(左子树) + count(右子树) + 1。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int countNodes(TreeNode root) {
            if(root==null) return 0;
            TreeNode left = root, right = root;
            int leftCount = 0;
            while(left!= null) {
                left = left.left;
                leftCount ++;
            }
            int rightCount = 0;
            while(right != null) {
                right = right.right;
                rightCount ++;
            }
            if(leftCount==rightCount) {
                return (2<<(leftCount-1)) - 1;
            } else {
                return countNodes(root.left) + countNodes(root.right) + 1;
            }
        }
        
        
    }
    

      

  • 相关阅读:
    开发常见错误之 :Missing artifact com.sun:tools:jar 1.7.0
    开发常见错误之 : Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar
    kafka集群部署
    kafka
    Oracle 学习之触发器
    CloudSetuper
    erlang :打开界面工具的命令
    erlang 二进制中 拼接 变量或者函数 报错
    Python内部机制。
    AOP (面向切面编程)
  • 原文地址:https://www.cnblogs.com/wxisme/p/4728765.html
Copyright © 2020-2023  润新知