和中序遍历的方式类似,只是改变了添加值的时机,在最开始的时候。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
TreeNode cur = root;
while(cur!=null||!stack.isEmpty())
{
while(cur!=null)
{
result.add(cur.val);
stack.push(cur);
cur=cur.left;
}
cur=stack.pop().right;
}
return result ;
}
}
网友评论