美文网首页
144. Binary Tree Preorder Traver

144. Binary Tree Preorder Traver

作者: 夜皇雪 | 来源:发表于2016-12-16 08:13 被阅读0次

Binary Tree preorder iterator

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        if(root==null) return res;
        Stack<TreeNode> stack=new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur=stack.pop();
            res.add(cur.val);
            if(cur.right!=null) stack.push(cur.right);
            if(cur.left!=null) stack.push(cur.left);
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:144. Binary Tree Preorder Traver

      本文链接:https://www.haomeiwen.com/subject/ynqnmttx.html