LeetCode 144. 二叉树的前序遍历(Binary Tree Preorder Traversal)

时间:2021-01-27 06:58:20

144. 二叉树的前序遍历

144. Binary Tree Preorder Traversal

题目描述

给定一个二叉树,返回它的 前序 遍历。

LeetCode144. Binary Tree Preorder Traversal

示例:

输入: [1,null,2,3]

   1
\
2
/
3

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

Java 实现

Iterative Solution

import java.util.LinkedList;
import java.util.List;
import java.util.Stack; class TreeNode {
int val;
TreeNode left;
TreeNode right; TreeNode(int x) {
val = x;
}
} class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
result.add(node.val);
}
return result;
}
}

Recursive Solution

import java.util.LinkedList;
import java.util.List; class TreeNode {
int val;
TreeNode left;
TreeNode right; TreeNode(int x) {
val = x;
}
} class Solution {
List<Integer> result = new LinkedList<>(); public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return result;
}
result.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return result;
}
}

相似题目

参考资料