增加 0222.完全二叉树的节点个数 go版 (新增利用完全二叉树特性的递归解法)

新增利用完全二叉树特性的递归解法
This commit is contained in:
NevS 2021-06-18 22:45:20 +08:00 committed by GitHub
parent a72bbac31e
commit d971558d3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 0 deletions

View File

@ -335,6 +335,30 @@ func countNodes(root *TreeNode) int {
}
```
利用完全二叉树特性的递归解法
```go
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
leftH, rightH := 0, 0
leftNode := root.Left
rightNode := root.Right
for leftNode != nil {
leftNode = leftNode.Left
leftH++
}
for rightNode != nil {
rightNode = rightNode.Right
rightH++
}
if leftH == rightH {
return (2 << leftH) - 1
}
return countNodes(root.Left) + countNodes(root.Right) + 1
}
```
JavaScript: