簡體   English   中英

path.remove,二叉樹路徑總和

[英]path.remove, Binary Tree Path Sum

有一個關於二叉樹的基本Java示例的問題:給定一棵二叉樹,找到所有路徑中等於該給定目標數的節點之和(有效路徑是從根節點到任何葉節點的路徑。 )。 為什么我們需要path.remove(path.size() - 1); 當它穿過左,右節點時?

這是代碼示例:

public class Solution {

    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {


        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        ArrayList<Integer> path = new ArrayList<Integer>();
        path.add(root.val);
        helper(root, path, root.val, target, result);
        return result;
    }

    private void helper(TreeNode root,
                        ArrayList<Integer> path,
                        int sum,
                        int target,
                        List<List<Integer>> result) {

        // meet leaf
        if (root.left == null && root.right == null) {
            if (sum == target) {
                result.add(new ArrayList<Integer>(path));
            }
            return;
        }

        // go left
        if (root.left != null) {
            path.add(root.left.val);
            helper(root.left, path, sum + root.left.val, target, result);
            path.remove(path.size() - 1);
        }

        // go right
        if (root.right != null) {
            path.add(root.right.val);
            helper(root.right, path, sum + root.right.val, target, result);
            path.remove(path.size() - 1);
        }
    }
}

在這種情況下, 路徑是一種臨時設施。 在訪問左側並開始處理右側之后,如果該編沒有從path清除root.right.val ,則它不正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM