二叉树的前/中/后序遍历用递归方式非常容易实现,也较为容易理解,而采用迭代方式实现就更为复杂一些。
前序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); if(root==null){ return result; } stack.push(root); while(!stack.isEmpty()){ TreeNode temp = stack.pop(); result.add(temp.val); if(temp.right!=null){ stack.push(temp.right); } if(temp.left!=null){ stack.push(temp.left); } } return result; } }
|
中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root==null){ return result; } Deque<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; while(!stack.isEmpty() || cur!=null){ while(cur!=null){ stack.push(cur); cur = cur.left; } cur = stack.pop(); result.add(cur.val); cur = cur.right; } return result; } }
|
后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); if(root==null){ return result; } stack.push(root); while(!stack.isEmpty()){ TreeNode temp = stack.pop(); result.add(temp.val);
if(temp.left!=null){ stack.push(temp.left); } if(temp.right!=null){ stack.push(temp.right); } } Collections.reverse(result); return result; } }
|