class Iteration { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode curr = root;
class Mirris { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); TreeNode curr = root; while (curr != null) { if (curr.left == null) { ans.add(curr.val); curr = curr.right; } else { // 找到左子树的最右节点(前驱) TreeNode pre = curr.left; while (pre.right != null && pre.right != curr) { pre = pre.right; } if (pre.right == null) { // 建立线索 pre.right = curr; curr = curr.left; } else { // 线索已存在,说明左子树已遍历完 pre.right = null; // 恢复树结构 ans.add(curr.val); curr = curr.right; } } } return ans; } }
时间复杂度:O(n)
空间复杂度:O(1)
4.测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class Main { public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3);