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

LeetCode 144. Binary Tree Preorder Traversal 解题报告

时间:2016-02-24 09:49:00      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

144. Binary Tree Preorder Traversal

My Submissions
Total Accepted: 108336 Total Submissions: 278322 Difficulty: Medium

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

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    求一棵二叉树的先根遍历序。题目说了,递归的解法十分简单,能否用非递归的方式求解。

    每遍历一个节点的时候,将右孩子入栈。向左搜索直到为空时,弹栈。

    我的AC代码

public class BinaryTreePreorderTraversal {
	
	public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
			while (cur != null) {
				list.add(cur.val);
				if(cur.right != null) stack.add(cur.right);
				cur = cur.left;
			}
			if(!stack.isEmpty()) cur = stack.pop();
		}
        return list;
    }
}


LeetCode 144. Binary Tree Preorder Traversal 解题报告

标签:

原文地址:http://blog.csdn.net/bruce128/article/details/50716729

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