二叉树的所有路径
题目
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例
给出下面这棵二叉树:
所有根到叶子的路径为:
题解
简单的递归遍历,如果该节点为叶节点则将路径加入列表,否则继续将该节点加入路径字符串。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
List<String> pathList = new ArrayList<>();
getPath(root,pathList,new String(""));
return pathList;
}
public void getPath(TreeNode root,List<String> pathList,String path)
{
if (root == null)
{
return;
}
path = path + String.valueOf(root.val) + "->";
if (root.left == null && root.right == null)
{
pathList.add(path.substring(0,path.length()-2));
return;
}
else
{
getPath(root.left,pathList,path);
getPath(root.right,pathList,path);
}
}
}
Last Update 2016.9.18