zoukankan      html  css  js  c++  java
  • Java for LeetCode 222 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 2h nodes inclusive at the last level h.

    解题思路:

    计算完全二叉树节点,直接递归会TLE,一个不错的思路是判断是否为满二叉树,然后进行递归,JAVA实现如下:

        public int countNodes(TreeNode root) {
            if(root==null)
            	return 0;
            int leftHeight=1,rightHeight=1;
            TreeNode temp=root.left;
            while(temp!=null){
            	temp=temp.left;
            	leftHeight++;
            }
            temp=root.right;
            while(temp!=null){
            	temp=temp.right;
            	rightHeight++;
            }
            if(leftHeight==rightHeight)
            	return (1<<leftHeight)-1;
            return countNodes(root.left)+countNodes(root.right)+1;
        }
    
  • 相关阅读:
    Junit单元测试
    Stream流方法引用
    Stream流思想和常用方法
    算法
    函数式接口
    Zookeeper理解
    GreenPlum学习之(Share-nothing)架构
    链表反转问题
    KMP算法的java实现
    KMP详解之二
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4578779.html
Copyright © 2011-2022 走看看