144. Binary Tree Preorder Traversal

和中序遍历的方式类似,只是改变了添加值的时机,在最开始的时候。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        Stack stack = new Stack<>();
        List 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 ;
    }
}

你可能感兴趣的:(144. Binary Tree Preorder Traversal)