版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83622256
一、Description
Given a binary tree, return the preorder traversal of its nodes' values.
题目大意:输出一个二叉树的前序遍历序列。
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
二、Analyzation
两种思路:
- 通过前序递归,每次访问一个结点,把该结点的值加到list中,再访问它的左结点和右结点。
- 通过一个栈来将结点存储并以此弹出并访问,由于list中的顺序是先左后右,因此栈的加入是先右后左。
三、Accepted code
recursive version:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return list;
}
help(root);
return list;
}
public void help(TreeNode root) {
list.add(root.val);
if (root.left != null) {
help(root.left);
}
if (root.right != null) {
help(root.right);
}
}
}
iterative version:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
list.add(temp.val);
if (temp.right != null) {
stack.add(temp.right);
}
if (temp.left != null) {
stack.add(temp.left);
}
}
return list;
}
}