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"]
Solution:
Resursion.
Base case: if root==null return an empty list.
if root is a leaf, return root.val.
else return root.val+"->" + each binaryTreePaths(root.left) and root.val+"->" + each binaryTreePaths(root.right)
Resursion.
Base case: if root==null return an empty list.
if root is a leaf, return root.val.
else return root.val+"->" + each binaryTreePaths(root.left) and root.val+"->" + each binaryTreePaths(root.right)
public List<String> binaryTreePaths(TreeNode root) {
List<String> res=new ArrayList<String>();
if(root==null) return res;
if(root.left==null && root.right==null){
res.add(root.val+"");
return res;
}
List<String> leftNode=binaryTreePaths(root.left);
for(String s: leftNode){
res.add(root.val+"->"+s);
}
List<String> rightNode=binaryTreePaths(root.right);
for(String s: rightNode){
res.add(root.val+"->"+s);
}
return res;
}
No comments:
Post a Comment