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

Lettcode_257_Binary Tree Paths

时间:2015-10-27 00:33:29      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:算法   java   leetcode   面试   编程   

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49432057



Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   2     3
   5

All root-to-leaf paths are:

["1->2->5", "1->3"]


思路:

(1)题意为给定一棵树,找出所有从根到叶子节点的路径。

(2)该题实为树的深度优先遍历。本题是使用递归的方法来进行求解的,从根节点开始,若左子树不为空,则遍历左子树,若左子树的左孩子不为空,则遍历左孩子,否则遍历右孩子.....直到遍历完最后一个叶子节点为止。使用非递归算法,则需要设定一个栈来保存左右子树,也很好实现,这里不累赘了。

(3)详情见下方代码。希望本文对你有所帮助。


package leetcode;

import java.util.ArrayList;
import java.util.List;
import leetcode.utils.TreeNode;

public class Binary_Tree_Paths {

	public static void main(String[] args) {
		TreeNode r = new TreeNode(1);
		TreeNode r1 = new TreeNode(2);
		TreeNode r2 = new TreeNode(3);
		TreeNode r3 = new TreeNode(5);

		r.left = r1;
		r.right = r2;
		r1.right = r3;

		binaryTreePaths(r);
	}

	public static List<String> binaryTreePaths(TreeNode root) {
		List<String> result = new ArrayList<String>();

		if (root != null) {
			getpath(root, String.valueOf(root.val), result);
		}
		return result;
	}

	private static void getpath(TreeNode root, String valueOf,
			List<String> result) {
		if (root.left == null && root.right == null)
			result.add(valueOf);

		if (root.left != null) {
			getpath(root.left, valueOf + "->" + root.left.val, result);
		}

		if (root.right != null) {
			getpath(root.right, valueOf + "->" + root.right.val, result);
		}
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Lettcode_257_Binary Tree Paths

标签:算法   java   leetcode   面试   编程   

原文地址:http://blog.csdn.net/pistolove/article/details/49432057

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