美文网首页
144. Binary Tree Preorder Traver

144. Binary Tree Preorder Traver

作者: namelessEcho | 来源:发表于2017-10-04 00:00 被阅读0次

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

    /**
     * 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 ;
        }
    }
    

    相关文章

      网友评论

          本文标题:144. Binary Tree Preorder Traver

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