迭代法
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
result.add(root.val);
if (root.right != null) stack.push(root.right);
if (root.left != null) stack.push(root.left);
}
return result;
}
}
递归法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<Integer> result = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
if (root != null) {
result.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
}
return result;
}
}
网友评论