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
I. Java Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root == null) return result;
LinkedList<TreeNode> path = new LinkedList<TreeNode>();
path.push(root);
TreeNode temp;
while(!path.isEmpty()){
temp = path.peek();
if(temp.left != null){
path.push(temp.left);
}else if(temp.right != null){
path.push(temp.right);
}else{
result.add(listToString(path));
temp = path.pop();
while(!path.isEmpty()){
if(path.peek().left == temp
&& path.peek().right!=null){
path.push(path.peek().right);
break;
}
temp = path.pop();
}
}
}
return result;
}
public String listToString(LinkedList<TreeNode> path){
ListIterator<TreeNode> iterator = path.listIterator(path.size());
StringBuilder builder = new StringBuilder();
builder.append(iterator.previous().val);
while(iterator.hasPrevious()){
builder.append("->" + iterator.previous().val);
}
return builder.toString();
}
}
No comments:
Post a Comment