给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
TreeNode next=root;
List<Integer> res=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
while (next!=null||!stack.isEmpty())
{
if(next==null) next=stack.pop();//左子树已经为空,就可以遍历右子树了
res.add(next.val);
if(next.right!=null) stack.push(next.right);//将右子树入栈
next=next.left;//先遍历到的是左子树
}
return res;
}
}