1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func inorderTraversal(root *TreeNode) []int { ans := []int{} node := root for node != nil { if node.Left != nil { predecessor := node.Left for predecessor.Right != nil && predecessor.Right != node { predecessor = predecessor.Right } if predecessor.Right == nil { predecessor.Right = node node = node.Left } else { ans = append(ans, node.Val) node = node.Right predecessor.Right = nil } } else { ans = append(ans, node.Val) node = node.Right } } return ans }
|