(1) 二叉树的前序遍历:
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
res := make([]int,0)
res = append(res,root.Val)
res = append(res,preorderTraversal(root.Left)...)
res = append(res,preorderTraversal(root.Right)...)
return res
}
(2)二叉树的层序遍历
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return nil
}
res := make([][]int,0)
queue := []*TreeNode{root}
res = append(res, []int{root.Val})
for len(queue) > 0 {
l := len(queue)
level := make([]int,0)
for i := 0;i < l ;i++ {
if queue[0].Left != nil {
level = append(level,queue[0].Left.Val)
queue = append(queue,queue[0].Left)
}
if queue[0].Right != nil {
level = append(level,queue[0].Right.Val)
queue = append(queue,queue[0].Right)
}
queue = queue[1:]
}
if len(level) > 0 {
res = append(res, level)
}
}
return res
}
(3) 二叉树的最大深度
func calculateDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1+ max(calculateDepth(root.Left),calculateDepth(root.Right))
}
func max(x,y int)int {
if x >y {
return x
}
return y
}
(4) 合并二叉树
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
newRoot := &TreeNode{Val:root1.Val+root2.Val}
newRoot.Left = mergeTrees(root1.Left,root2.Left)
newRoot.Right = mergeTrees(root1.Right,root2.Right)
return newRoot
}
(5) 翻转二叉树
func mirrorTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left,root.Right = root.Right,root.Left
if root.Left != nil {
root.Left = mirrorTree(root.Left)
}
if root.Right != nil {
root.Right = mirrorTree(root.Right)
}
return root
}
(6)判断是否为二叉平衡树
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return abs(GetTreeDepth(root.Left)-GetTreeDepth(root.Right)) <=1&& isBalanced(root.Left)&& isBalanced(root.Right)
}
func GetTreeDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1+ max(GetTreeDepth(root.Left),GetTreeDepth(root.Right))
}
(7) 是否完全二叉树
func isCompleteTree(root *TreeNode) bool {
queue,found := []*TreeNode{root},false
for len(queue) >0 {
node:= queue[0]
queue = queue[1:]
if node == nil {
found = true
} else {
if found {
return false
}
queue = append(queue,node.Left,node.Right)
}
}
return true
}
(8)二叉搜索树的最近公共祖先
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || p == nil ||q == nil{
return nil
}
rVal := root.Val
pVal := p.Val
qVal := q.Val
if rVal == pVal || rVal == qVal {
return root
}
if pVal<rVal &&qVal <rVal {
return lowestCommonAncestor(root.Left,p,q)
}
if pVal>rVal && qVal > rVal {
return lowestCommonAncestor(root.Right,p,q)
}
return root
}
(9) 二叉树的最近公共祖先
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || p == nil || q == nil {
return nil
}
if root.Val == p.Val ||root.Val == q.Val {
return root
}
left := lowestCommonAncestor(root.Left,p,q)
right := lowestCommonAncestor(root.Right,p,q)
if left != nil && right != nil {
return root
}
if left != nil {
return left
}
return right
}