所有題目源代碼:Git地址
題目
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
方案:遞歸、迭代+棧
- 同94,改個順序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> res = new LinkedList<>();
private Stack<TreeNode> stack = new Stack<>();
public List<Integer> preorderTraversal(TreeNode root) {
// 遞歸解法
// if (root==null) return res;
// res.add(root.val);
// if(root.left!=null) preorderTraversal(root.left);
// if(root.right!=null) preorderTraversal(root.right);
// return res;
//迭代解法
//頭先加、轉左節點、存右邊節點
TreeNode cur = root;
while(cur!=null||!stack.isEmpty()){
if(cur!=null){
res.add(cur.val);
stack.push(cur.right);
cur = cur.left;
}else{
cur = stack.pop();
}
}
return res;
}
}
複雜度計算
- 時間複雜度:O(n),n代表元素個數
- 空間複雜度:O(n)