码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]144. Binary Tree Preorder Traversal二叉树前序遍历

时间:2018-01-26 10:58:29      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:val   logs   color   traversal   www   树的遍历   class   html   bsp   

关于二叉树的遍历请看:

http://www.cnblogs.com/stAr-1/p/7058262.html

/*
    考察基本功的一道题,迭代实现二叉树前序遍历
     */
    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;
    }

 

[LeetCode]144. Binary Tree Preorder Traversal二叉树前序遍历

标签:val   logs   color   traversal   www   树的遍历   class   html   bsp   

原文地址:https://www.cnblogs.com/stAr-1/p/8358089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!