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开始一直记录路径上的所有节点,然后当遍历到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));
}
}
}
网友评论