func PreOrder(root *Tree) []int { var result []int if root == nil { return result } result = append(result, root.Val) result = append(result, PreOrder(root.Left)...) result = append(result, PreOrder(root.Right)...) return result }
func PreOrderNonRecursive(root *Tree) []int { var result []int if root == nil { return result } stack := list.New() p := root for p != nil || stack.Len() != 0 { for p != nil { result = append(result, p.Val) stack.PushBack(p) p = p.Left } if stack.Len() != 0 { node := stack.Back() stack.Remove(node) p = node.Value.(*Tree).Right } } return result }
中序递归
1 2 3 4 5 6 7 8 9 10
func InOrder(root *Tree) []int { var result []int if root == nil { return nil } result = append(result, PreOrder(root.Left)...) result = append(result, root.Val) result = append(result, PreOrder(root.Right)...) return result }
func InOrderNonRecursive(root *Tree) []int { var result []int if root == nil { return result } stack := list.New() p := root for p != nil || stack.Len() != 0 { for p != nil { stack.PushBack(p) p = p.Left } if stack.Len() != 0 { node := stack.Back() stack.Remove(node) result = append(result, node.Value.(*Tree).Val) p = node.Value.(*Tree).Right } } return result }
后序递归
1 2 3 4 5 6 7 8 9 10
func PostOrder(root *Tree) []int { var result []int if root == nil { return nil } result = append(result, PreOrder(root.Left)...) result = append(result, PreOrder(root.Right)...) result = append(result, root.Val) return result }