美文网首页
144. Binary Tree Preorder Traver

144. Binary Tree Preorder Traver

作者: 成江 | 来源:发表于2018-10-12 23:39 被阅读7次
/**
 * 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) {
        List<Integer> ans = new ArrayList<>();
        if (root == null)
            return ans;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            root = stack.pop();
            ans.add(root.val);
            if (root.right != null)
                stack.push(root.right);
            if (root.left != null)
                stack.push(root.left);
        }
        return ans;
    }
}

相关文章

网友评论

      本文标题:144. Binary Tree Preorder Traver

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