Subject description:
An input binary tree root node and an integer, the binary print values of nodes in the input path and all integers. Forming a path to the path definition begins from the root node of the tree down to the leaf node has been traversed nodes. (Note: the return value in the list, a large array Array front)
Example above: integer input 22, the path may be printed with a (10,5,7) and (10, 12)
Ideas:
The whole process using the depth-first traversal DFS.
Code:
package offer;
import org.omg.PortableInterceptor.INACTIVE;
import sun.reflect.generics.tree.Tree;
import java.util.ArrayList;
import java.util.Stack;
public class TestNo24 {
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
TreeNode node1 = new TreeNode(5);
TreeNode node2 = new TreeNode(12);
TreeNode node3 = new TreeNode(4);
TreeNode node4 = new TreeNode(7);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
System.out.println(new TestNo24().FindPath(root,22));
}
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null ){
return ret;
}
//递归调用
findPath(root,target,new ArrayList<>());
return ret;
}
public void findPath(TreeNode root, int target, ArrayList<Integer> cache){
if(root == null){
return;
}
int val = root.val;
int remainVal = target-val;
//当前节点列表
cache.add(val);
if(remainVal == 0 && root.left == null && root.right == null){
ret.add(new ArrayList<>(cache));
}
//处理叶子节点
findPath(root.left,remainVal,cache);
findPath(root.right,remainVal,cache);
//回溯到上一个节点
cache.remove(cache.size()-1);
}
}