package main
import (
tree "awesomeProject/interview/Tree"
"fmt"
)
//非递归中序遍历(left->root->right)
func inorderTraversal(root *tree.Node) []int {
result := make([]int, 0)
if root == nil {
return result
}
stack := make([]*tree.Node, 0)
//首先判断左子树是否为空,然后判断根节点是否为空,先把左子树遍历完成
for len(stack) > 0 || root != nil {
//只有右节点才进行第二次遍历
for root != nil {
//左节点入栈
stack = append(stack, root)
//一直遍历完左子树
root = root.Left
}
//左子树已经遍历完,压入结果
val := stack[len(stack)-1]
stack = stack[:len(stack)-1]
result = append(result, val.Val)
root = val.Right //右节点
}
return result
}
func main() {
/*
1
/\
2 3
/\ /\
4 56 7
*/
root := tree.NewNode(1)
left1 := tree.NewNode(2)
right1 := tree.NewNode(3)
root.Left = left1
root.Right = right1
left2 := tree.NewNode(4)
right2 := tree.NewNode(5)
left1.Left = left2
left1.Right = right2
left3 := tree.NewNode(6)
right3 := tree.NewNode(7)
right1.Left = left3
right1.Right = right3
fmt.Println(inorderTraversal(root)) //[4 2 5 1 6 3 7]
}