试题:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/
2 3
5
Output: [“1->2->5”, “1->3”]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
代码:
深度优先遍历,只不过要注意下遍历终止条件是左右节点为null,比以往遍历有点区别。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> out = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root==null) return out;
find(root,""+root.val);
return out;
}
private void find(TreeNode root, String path){
if(root.left==null&&root.right==null){
out.add(path);
}
if(root.left!=null) find(root.left, path+"->"+root.left.val);
if(root.right!=null) find(root.right, path+"->"+root.right.val);
}
}