题目:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list= new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root==null)
return list;
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;
}