码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 144 Binary Tree Preorder Traversal

时间:2015-06-04 22:33:35      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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].

二叉树的前序遍历,根节点→左子树→右子树

解题思路一:

递归实现,JAVA实现如下:

    public List<Integer> preorderTraversal(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		if (root == null)
			return list;
		list.add(root.val);
		list.addAll(preorderTraversal(root.left));
		list.addAll(preorderTraversal(root.right));
		return list;
    }

 解题思路二:

使用stack实现,JAVA实现如下:

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

 

Java for LeetCode 144 Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4553030.html

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