二叉樹中和爲某一值的路徑_java

輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> path = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
          if(root == null)
              return  pathList; 
          path.add(root.val);
          if(root.left == null && root.right == null && target == root.val)
          {
                pathList.add(new ArrayList<Integer>(path));
          }
          if(root.val <= target && root.left != null){
              FindPath(root.left,target-root.val); 
          }  
          if(root.val <= target && root.right != null)
          {
              FindPath(root.right,target-root.val); 
          }   
          path.remove(path.size()-1);//回退到父節點
          return pathList;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章