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;
        }
    
  • 相关阅读:
    Qt之Threads和QObjects
    Qt之可重入与线程安全
    Qt之线程基础
    Qt之QLineEdit
    Qt之属性系统
    Django框架
    web框架起源
    django查看数据库
    jQuery
    BOM&DOM
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4578779.html
Copyright © 2011-2022 走看看