樹-Path Sum II(指定和,求根到葉子的路徑)

題目:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

思考:

想了大半天,參考了往上的辦法,深度優先搜索,先從根節點的左兒子的左兒子...一直到葉子位置,那麼這就是第一條路徑了,路徑和爲參數就加入保存路徑的list,否則刪掉這個葉子,查看這個節點的兄弟試試看,也就是這個葉子的父節點的有兒子(有的話),採用遞歸,以此類推。

代碼(java):

/**
 * 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<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> totalPath = new ArrayList<List<Integer>>();
		int total = 0;
		List<Integer> currentPath = new ArrayList<Integer>();
			
		find(root, sum, currentPath, total, totalPath);


		return totalPath;
    }
    
    
    
    
    
    public void find(TreeNode root, int sum, List<Integer> currentPath, int total, List<List<Integer>> totalPath){
		
		if(root == null){
			return;
		}
		currentPath.add(root.val);
		total = total + root.val;
		
		
		if(root.left == null && root.right == null && total == sum){		
			totalPath.add(new ArrayList(currentPath));	
			return;
		}
		
		//首先會一直遍歷left,然後纔是慢慢的往上走,取查看他的兄弟,所以需要刪除最後一個!
		if(root.left != null){
			//currentPath.add(root.val);
			//total = total + root.val;
			find(root.left, sum, currentPath, total, totalPath);
			
			currentPath.remove(currentPath.size() - 1);
		}
		
		if(root.right != null){
			//currentPath.add(root.val);
			//total = total + root.val;
			find(root.right, sum, currentPath, total, totalPath);
			
			currentPath.remove(currentPath.size() - 1);
		}
		
	}
}


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