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

Java [Leetcode 257]Binary Tree Paths

时间:2016-02-06 18:24:31      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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

解题思路:

使用递归法。

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if(root != null)
        	searchTree(res, root, "");
        return res;
    }
	 
	public void searchTree(List<String> res, TreeNode root, String connection){
		if(root.left == null && root.right == null)
			res.add(connection + root.val);
		if(root.left != null)
			searchTree(res, root.left, connection + root.val + "->");
		if(root.right != null)
			searchTree(res, root.right, connection + root.val + "->");
	}
}

  

 

Java [Leetcode 257]Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5184154.html

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