//完全二叉树的节点个数
func countNodes(root *TreeNode) int {
if root==nil{
return 0
}
return countNodes(root.Left)+countNodes(root.Right)+1
}
//完全二叉树的节点个数
func countNodesV1(root *TreeNode) int {
if root==nil{
return 0
}
lt:=list.New()
lt.PushFront(root)
c:=lt.Len()
for lt.Len()>0{
node:=lt.Remove(lt.Back()).(*TreeNode)
if node.Right!=nil{
lt.PushBack(node.Right)
c=c+lt.Len()
}
if node.Left!=nil{
lt.PushBack(node.Left)
c=c+lt.Len()
}
}
return c
}
二叉树所有路径
//257. 二叉树的所有路径
func binaryTreePaths(root *TreeNode) []string {
var res []string
if root==nil{
return res
}
var travel func(root *TreeNode,s string)
travel= func(root *TreeNode, s string) {
if root.Right==nil && root.Left==nil{
v := s + strconv.Itoa(root.Val)
res = append(res, v)
}
s = s + strconv.Itoa(root.Val) + "->"
if root.Right!=nil{
travel(root.Right,s)
}
if root.Left!=nil{
travel(root.Left,s)
}
}
travel(root,"")
return res
}
//257. 二叉树的所有路径
func binaryTreePathsV2(root *TreeNode) []string {
var res []string
if root==nil{
return res
}
lt:=list.New()
lt.PushBack(root)
var s []string
s=append(s, "")
for lt.Len()>0{
l:=lt.Len()
node:=lt.Remove(lt.Back()).(*TreeNode)
if node==nil{
break
}
path:=s[l-1]
s=s[:l-1]
if node.Left==nil && node.Right==nil{
res = append(res, path+strconv.Itoa(node.Val))
continue
}
fmt.Printf("======s:%v \n",s)
if node.Right!=nil{
lt.PushBack(node.Right)
s = append(s, path+strconv.Itoa(node.Val)+"->")
}
if node.Left!=nil{
lt.PushBack(node.Left)
s = append(s, path+strconv.Itoa(node.Val)+"->")
}
}
return res
}