给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
_____________________________________________________________________________________________________
方法一:
暴力的遍历算法:
采用任何一种遍历算法,前中后序,或则是中序都可以得到结果。
代码如下:
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
r := countNodes(root.Left)
l := countNodes(root.Right)
return r+l+1
}
方法二:
根据完全二叉树定义,可以先遍历最左边的一条路径,找到最大的层数depth,然后从向右,找到第一条路径上节点数小于depth的路径,并记录之前所有路径上节点个数等于depth的路径数count,再根据depth和count计算所有的节点数.
代码如下:
func countNodes(root *TreeNode) int {
count := 0
if root == nil {
return 0
}
t := root
for t != nil {
count++
t = t.Left
}
res := 0
flag := false
Run(count,1,&res,root,&flag)
p := 1
k := 1
for i:=1;i<count-1;i++ {
p += k<<1
k = k<<1
}
return res+p
}
func Run(limit , last int,rec *int , root *TreeNode,flag *bool ) {
if *flag == true {
return
}
if root.Left == nil && root.Right == nil {
if last == limit && limit != 1 {
(*rec)++
} else {
*flag = true
}
return
}
if root.Left != nil {
Run(limit,last+1,rec,root.Left,flag)
}
if root.Right != nil {
Run(limit,last+1,rec,root.Right,flag)
}
}