zoukankan      html  css  js  c++  java
  • leetcode面试准备:Count Complete Tree Nodes

    1 题目

    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 2h nodes inclusive at the last level h.

    接口:public int countNodes(TreeNode root);

    2 思路

    思路1

    用暴力法:不考虑完全二叉树的特性,直接遍历求节点数。---超时
    复杂度: Time:O(N); Space:O(log N)

    思路2

    完全二叉树的节点数,可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 countNodes(root.left) + 1 + countNodes(root.right)
    复杂度: Time:O(log N); Space:O(log N)

    思路3

    二分查找的思想,感觉和思路2差不多。但是代码写出来的效率高一些。
    复杂度: Time:O(log N); Space:O(1)

    3 代码

    思路1

    	public int countNodes0(TreeNode root) {
    		if (root == null)
    			return 0;
    		return countNodes(root.left) + 1 + countNodes(root.right);
    	}
    

    思路2

    	public int countNodes(TreeNode root) {
    		if (root == null)
    			return 0;
    		int leftHigh = 0, rightHigh = 0;
    		TreeNode lchild = root.left, rchild = root.right;
    		for (; lchild != null;) {
    			leftHigh++;
    			lchild = lchild.left;
    		}
    		for (; rchild != null;) {
    			rightHigh++;
    			rchild = rchild.right;
    		}
    
    		if (leftHigh == rightHigh) {
    			return (2 << leftHigh) - 1;
    		} else {
    			return countNodes(root.left) + 1 + countNodes(root.right);
    		}
    	}
    

    4 总结

    计算阶乘的注意: (2 << leftHigh) - 1才不会超时,用Math.pow()超时。
    二分查找思想,自己很不熟练。多找题目联系联系。

    5 参考

  • 相关阅读:
    Pandas索引和选择数据
    Pandas选项和自定义
    Pandas字符串和文本数据
    Pandas排序
    Pandas迭代
    Pandas重建索引
    Pandas函数应用
    Pandas描述性统计
    Pandas基本功能
    nyoj 234 吃土豆
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4703278.html
Copyright © 2011-2022 走看看