二叉樹的前序遍歷
題目描述
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
解題思路
個人AC
迭代法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> output = new LinkedList<>();
if (root == null) return output;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.pop();
output.add(top.val);
if (top.right != null) stack.push(top.right);
if (top.left != null) stack.push(top.left);
}
return output;
}
}
時間複雜度: ;
空間複雜度: 。
遞歸法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> output = new LinkedList<>();
preOrder(root, output);
return output;
}
private void preOrder(TreeNode root, List<Integer> output) {
if (root == null) return;
output.add(root.val);
preOrder(root.left, output);
preOrder(root.right, output);
}
}
時間複雜度: ;
空間複雜度: 。
最優解
同上。