首页 > 其他 > 详细

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

时间:2018-11-13 19:08:21      阅读:151      评论:0      收藏:0      [点我收藏+]

【题目】

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!