Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1
/
2 3
5
All root-to-leaf paths are:
[ "1->2->5", "1->3"]
遇到二叉樹的題一般都會用到遞歸遍歷,這題就是一個變形,要找所以的路徑,思路就是從root開始一直記錄路徑上的所有節(jié)點,然后當遍歷到leaf的時候,我們就把路徑加入到result中。
把path存在字符串中做遞歸剛開始也沒想到,后來看了別人的思路覺得代碼寫起來簡潔很多,所有就you'hua'le'xia
/**
* 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) {
// Write your code here
List<String> result = new ArrayList<String>();
if (root != null) {
findPath(result, root, String.valueOf(root.val));
}
return result;
}
public void findPath(List<String> result, TreeNode p, String path) {
if(p == null) {
return ;
}
if (p.left == null && p.right == null) {
result.add(path);
return ;
}
if(p.left != null) {
findPath(result, p.left, path + "->" + String.valueOf(p.left.val));
}
if(p.right != null) {
findPath(result, p.right, path + "->" + String.valueOf(p.right.val));
}
}
}