Java [Leetcode 257]Binary Tree Paths

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java [Leetcode 257]Binary Tree Paths相关的知识,希望对你有一定的参考价值。

题目描述:

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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode257]Binary Tree Paths

LeetCode 257. Binary Tree Paths

leetcode?python 257. Binary Tree Paths

leetcode 257. Binary Tree Paths

Leetcode 257: Binary Tree Paths

Leetcode 257 Binary Tree Paths 二叉树 DFS