Depth First Traversal Binary Tree
Question:
Binary Tree Path
Given a binary tree, return all root-to-leaf paths.
public List<String> binaryTreePaths(TreeNode root) {
List<String> res=new LinkedList<String>();
if(root==null) return res;
dfs(root,""+root.val,res);
return res;
}
public void dfs(TreeNode root, String tmp, List<String> res){
if(root.left==null&&root.right==null) {
res.add(tmp);
return;
}
if(root.left!=null) dfs(root.left, tmp+"->"+root.left.val,res);
if(root.right!=null) dfs(root.right, tmp+"->"+root.right.val, res);
}
Print out all GrandPa-Father-Me path
public List<String> binaryTreePaths(TreeNode root) {
List<String> res=new LinkedList<String>();
if(root==null) return res;
dfs(root,""+root.val,res,1);
for(String a:res) System.out.println(a);
return res;
}
public void dfs(TreeNode root,String tmp, List<String> res, int count){
if(root.left!=null&&count==1) dfs(root.left,""+root.left.val,res,1);
if(root.right!=null&&count==1) dfs(root.right, ""+root.right.val,res,1);
if(count==3){
res.add(tmp);
return;
}
if(root.left!=null) dfs(root.left,tmp+"->"+root.left.val,res,count+1);
if(root.right!=null) dfs(root.right,tmp+"->"+root.right.val,res,count+1);
}
Print Ancestors of a given node in Binary Tree
Define function List<Node> getAncestor(Node root, int target)
public List<Node> getAncestor(Node root, int target){
LinkedList<Node> res=new LinkedList<Node>();
if(root==null) return res;
dfs(root,target,res);
return res;
}
public boolean dfs(TreeNode root, int target, LinkedList<Node> res){
if(root.val==target) return true;
res.push(root);
if(root.left!=null){
if(dfs(root.left,target,res)) return true;
}
if(root.right!=null){
if(dfs(root.right,target,res) return true;
}
res.pop();
}