所有題目源代碼:Git地址
題目
給定一個二叉樹,返回它的 後序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [3,2,1]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
方案:遞歸、迭代+棧
- 後續的迭代用棧實現,和前序和中序有點不同,就是需要反着插入數組,因爲父節點不太好弄得符合邏輯。。。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private LinkedList<Integer> res = new LinkedList<>( );
private Stack<TreeNode> stack = new Stack<>( );
public List<Integer> postorderTraversal(TreeNode root) {
// // 遞歸解法
if (root==null) return res;
// if(root.left!=null) postorderTraversal(root.left);
// if(root.right!=null) postorderTraversal(root.right);
// res.add(root.val);
// return res;
//迭代解法
//正常遍歷,就是反着插入就行
stack.push(root);
TreeNode cur ;
while (!stack.isEmpty( )) {
cur = stack.pop();
res.addFirst(cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if(cur.right!=null){
stack.push(cur.right);
}
}
return res;
}
}
複雜度計算
- 時間複雜度:O(n)
- 空間複雜度:O(n)