Sword refers to offer 34. The path in the binary tree that sums to a certain value

Sword refers to offer 34. The path in the binary tree that sums to a certain value

Title description

Insert picture description here

Problem-solving ideas

Note that and leetcode 46. 全排列, leetcode 78. 子集, leetcode 77. 组合backtracking difference, select list of both is the same, are all the children nodes, the main difference lies in the path of the recording mode, this record is the root problem, which is recorded by children.

  • In the above three backtracking questions, every time a node is faced with multiple choices, if one of the choices is made, the choice of the child node is added to the path . Because the root node is empty, the initial selection is from the child nodes of the root node.
    So the operation of making selections and canceling selections is in the for loop, that is, you need to cancel the selection every time you visit a child. After traversing in this way, only the visit of the root node will be ignored.

  • When choosing this question (including other binary trees, graphs, and recursive ideas of dp), the node that is currently being selected is added to the path .
    Therefore, the operation of making selection and canceling the selection is outside the for loop, that is, after all the children are visited, the selection of the root node is canceled once. After traversing in this way, the entire tree (including the root node) will be visited.

Complete code:

class Solution {
    
    

     public List<List<Integer>> res = new LinkedList<>();

    public List<List<Integer>> pathSum(TreeNode root, int target) {
    
    
        if (root == null) return res;
        
        LinkedList<Integer> track = new LinkedList<>();
        backtrack(root, target, track);
        return res;
    }
    //定义:打印出从root节点一直到叶子节点的路径和为target的路径
    public void backtrack(TreeNode root, int target, LinkedList<Integer> track) {
    
    
        //空节点直接返回
        if (root == null) return;
        // 到达叶节点
        if (root.left == null && root.right == null && target == root.val) {
    
    
            track.add(root.val);
            res.add(new LinkedList<>(track));
            track.removeLast();
            return;
        }
        track.add(root.val);
        //在已将root添加进路径的基础上,分别打印出左右子树的路径
        backtrack(root.left, target - root.val, track);
        backtrack(root.right, target - root.val, track);

        track.removeLast();
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115180492