关闭

LeetCode Count Complete Tree Nodes

标签: javaleetcodeBinary Tree
172人阅读 评论(0) 收藏 举报
分类:

Description:

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.

Solution:

参考了这位的,有和Andrew Ng合影的照片!

点击打开链接

import java.util.*;

public class Solution {

	public int countNodes(TreeNode root) {
		if (root == null)
			return 0;

		int leftH = getLeftHeight(root);
		int rightH = getRightHeight(root);

		if (leftH == rightH) {
			return (1 << leftH) - 1;
		} else {

			return countNodes(root.left) + countNodes(root.right) + 1;
		}
	}

	int getLeftHeight(TreeNode root) {
		TreeNode temp = root;
		int len = 0;
		while (temp != null) {
			temp = temp.left;
			len++;
		}
		return len;
	}

	int getRightHeight(TreeNode root) {
		TreeNode temp = root;
		int len = 0;
		while (temp != null) {
			temp = temp.right;
			len++;
		}
		return len;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61630次
    • 积分:3254
    • 等级:
    • 排名:第10408名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论