/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classTreeNode{ int val; TreeNode left; TreeNode right;
TreeNode(int x) { val = x; } }
classSolution{ public List<Integer> inorderTraversal(TreeNode root){ List<Integer> r = new LinkedList<>(); TreeNode t = null;
while (root != null) { if (root.left != null) { t = root.left; while (t.right != null && t.right != root) { t = t.right; } if (t.right == null) { t.right = root; root = root.left; } else { r.add(t.right.val); root = root.right; t.right = null; }
} else { r.add(root.val); root = root.right; }
} return r; }
voidtest(){ TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right = new TreeNode(3); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); List<Integer> r = inorderTraversal(root); for (int i : r) { System.out.print(i + " "); // 4 2 5 1 6 3 7 } } }
classSolution2{ public List<Integer> inorderTraversal(TreeNode root){ List<Integer> r = new LinkedList<>(); Stack<TreeNode> s = new Stack<>(); while (root != null || !s.isEmpty()) { while (root != null) { s.push(root); root = root.left; } root = s.pop(); r.add(root.val); root = root.right; } return r; }
voidtest(){ TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right = new TreeNode(3); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); List<Integer> r = inorderTraversal(root); for (int i : r) { System.out.print(i + " "); // 4 2 5 1 6 3 7 } } }
classSolution1{ List<Integer> r;
public List<Integer> inorderTraversal(TreeNode root){ r = new LinkedList<>(); visit(root); return r; }
voidvisit(TreeNode root){ if (root.left != null) { visit(root.left); } r.add(root.val); if (root.right != null) { visit(root.right); } }
voidtest(){ TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right = new TreeNode(3); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); List<Integer> r = inorderTraversal(root); for (int i : r) { System.out.print(i + " "); // 4 2 5 1 6 3 7 } } } }