题解 | #求二叉树的前序遍历#
求二叉树的前序遍历
https://www.nowcoder.com/practice/501fb3ca49bb4474bf5fa87274e884b4
import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
list.add(temp.val);
if(temp.right != null)
stack.push(temp.right);
if(temp.left != null)
stack.push(temp.left);
}
return list;
}
}
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
list.add(temp.val);
if(temp.right != null)
stack.push(temp.right);
if(temp.left != null)
stack.push(temp.left);
}
return list;
}
}