二叉树类
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
前序:
public class Solution { public List<Integer> preorderTraversal1(TreeNode root) { List<Integer> list = new LinkedList<>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<>(); stack.add(root); while (!stack.isEmpty()) { TreeNode current = stack.pop(); list.add( current.val); if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } return list; } }
中序:
public class Solution { public List<Integer> inorderTraversal1(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.left; } current = stack.pop(); list.add(current.val); current = current.right; } return list; } }
后序:
public class Solution { public List<Integer> postorderTraversal1(TreeNode root) { List<Integer> list = new LinkedList<>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<>(); stack.add(root); while (!stack.isEmpty()) { TreeNode current = stack.pop(); list.add(0, current.val); if (current.left != null) { stack.push(current.left); } if (current.right != null) { stack.push(current.right); } } return list; } }