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"]
给定一个二叉树,输出从根到叶子节点的路径。用递归来完成,代码如下:
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> list = new ArrayList<String>();
if(root == null) return list;
getPath(root, String.valueOf(root.val), list);
return list;
}
public void getPath(TreeNode root, String s, List<String> list) {
if(root.left == null && root.right == null)
list.add(s);
if(root.left != null)
getPath(root.left, s + "->" + root.left.val, list);
if(root.right != null)
getPath(root.right, s + "->" + root.right.val, list);
}
}
本文介绍如何使用递归算法解决二叉树中从根节点到叶子节点的所有路径问题,通过实例代码展示解决方案。
394

被折叠的 条评论
为什么被折叠?



