0%

June Leetcoding Challenge(6.23)

LeetCode六月挑战(6.23 )Count Complete Tree Nodes LeetCode 222 解题方案Given a complete binary tree, count the number of nodes.

Note:

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.

Example:

1
2
3
4
5
6
7
8
Input: 
1
/ \
2 3
/ \ /
4 5 6

Output: 6

思路

在这里插入图片描述

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
int left = leftNode(root);
int right = rightNode(root);
return left == right ? (1<<left) -1 : 1 + countNodes(root.left)+countNodes(root.right);

}

public int leftNode(TreeNode root){
return root == null? 0:1+leftNode(root.left);
}

public int rightNode(TreeNode root){
return root == null? 0:1+rightNode(root.right);
}
}
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.23)

文章作者:Jungle

发布时间:2020年06月23日 - 08:35

最后更新:2020年06月24日 - 09:29

原始链接:http://yoursite.com/2020/06/23/LeetCodeJuneChallenge23th/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels