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

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

时间:2018-11-13 20:47:25      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:完成   roo   NPU   style   link   span   nbsp   empty   思路   

【题目】

Given a binary tree, return the preordertraversal of its nodes‘ values.

Example:

Input: [1,null,2,3]
   1
         2
    /
   3

Output: [1,2,3]

【思路】

有参考,好机智,使用堆栈压入右子树,暂时存储。

左子树遍历完成后遍历右子树。

【代码】

/**
 * 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) {
        LinkedList<Integer> ans=new LinkedList<Integer>();
        Stack<TreeNode> tmp=new Stack<TreeNode>();
        while(root!=null){
            ans.add(root.val);
            if(root.right!=null){
                tmp.push(root.right);
            }
            root=root.left;
            if(root==null&&!tmp.isEmpty()){
                root=tmp.pop();
            }
        }
        return ans;
    }
}

 

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

标签:完成   roo   NPU   style   link   span   nbsp   empty   思路   

原文地址:https://www.cnblogs.com/inku/p/9953915.html

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