LeetCode Count Complete Tree Nodes

原创 2015年07月10日 11:16:01

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;
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode - Count Complete Tree Nodes

题目: Count Complete Tree Nodes   Given a complete binary tree, count the number of nodes...

leetCode(19):Count Complete Tree Nodes

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

LeetCode 222. Count Complete Tree Nodes 题解——Java

题目链接:https://leetcode.com/problems/count-complete-tree-nodes/#/description 题目要求:计算完全二叉树的节点个数 思...

leetcode -- 222. Count Complete Tree Nodes【子问题划分】

题目 Given a complete binary tree, count the number of nodes. Definition of a complete binary tree fr...

LeetCode——Count Complete Tree Nodes

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left...

Count Complete Tree Nodes -- leetcode

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

leetcode--Count Complete Tree Nodes

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

(未完成!)Leetcode 222. Count Complete Tree Nodes

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

leetcode222---Count Complete Tree Nodes(求完全二叉树节点数)

问题描述:Given a complete binary tree, count the number of nodes.In a complete binary tree every level, ...

#leetcode#Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)