LeetCode 145 Binary Tree Postorder Traversal (後序遍歷二叉樹)
阿新 • • 發佈:2019-02-05
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
遞迴:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void DFS(TreeNode root, List<Integer> ans) { if(root == null) { return; } DFS(root.left, ans); DFS(root.right, ans); ans.add(root.val); } public List<Integer> postorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); DFS(root, ans); return ans; } }
非遞迴:後序遍歷左右中,考慮到棧的先進先出,故先將右子樹壓棧,兩種情況記錄答案出棧,1是遇到葉子,2是父節點的子節點已經被訪問過,根據壓棧順序,可以保證這樣可以完成後序遍歷
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); Stack<TreeNode> stk = new Stack<>(); if(root != null) { stk.push(root); } TreeNode cur = null; TreeNode pre = null; while(!stk.empty()) { cur = stk.peek(); if(cur.left == null && cur.right == null) { ans.add(cur.val); pre = cur; stk.pop(); } else if(pre != null && (cur.left == pre || cur.right == pre)) { ans.add(cur.val); pre = cur; stk.pop(); } else { if(cur.right != null) { stk.push(cur.right); } if(cur.left != null) { stk.push(cur.left); } } } return ans; } }