程式碼隨想錄演算法訓練營第十八天| 513. 找樹左下角的值 112. 路徑總和 113. 路徑總和 II

jeasonGo發表於2024-03-23

513. 找樹左下角的值
https://leetcode.cn/problems/find-bottom-left-tree-value/description/

public int findBottomLeftValue(TreeNode root) {
        int val = 0;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(root);
        while (!deque.isEmpty()){
            int len = deque.size();
            for (int i = 0; i < len; i++) {
                TreeNode node = deque.poll();
                if (i == 0) val = node.val;
                if (node.left != null) deque.offer(node.left);
                if (node.right != null) deque.offer(node.right);
            }
        }
        return val;
    }

總結:層序遍歷
112. 路徑總和
https://leetcode.cn/problems/path-sum/description/

public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        boolean sum = sum(root, targetSum);
        return sum;
    }
    public boolean sum(TreeNode node,int sum){
        if (node.left == null && node.right == null) {
            return sum - node.val == 0; // 到達葉子節點時判斷路徑和是否等於目標和
        }
        boolean sumLeft = false;
        boolean sumRight = false;
        if (node.left != null) {
            sumLeft = sum(node.left, sum - node.val);
        }
        if (node.right != null){
            sumRight = sum(node.right, sum - node.val);
        }
        return sumLeft || sumRight;
    }

總結:遞迴到葉子節點,判斷是否合理
113. 路徑總和 II
https://leetcode.cn/problems/path-sum-ii/description/

public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> resList = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        if (root == null) return resList;
        pathSSum(root,targetSum,resList,path);
        return resList;
    }
    public void pathSSum(TreeNode node,int targetSum,List<List<Integer>> resList,List<Integer> path){
        if (node.left == null && node.right == null){
            if (targetSum - node.val == 0){
                path.add(node.val);
                resList.add(new ArrayList<>(path));
                path.remove(path.size() - 1); //回溯
            }
            return;
        }
        if (node.left != null){
            path.add(node.val);
            pathSSum(node.left,targetSum - node.val,resList,path);
            path.remove(path.size() - 1); //回溯
        }
        if (node.right != null){
            path.add(node.val);
            pathSSum(node.right,targetSum - node.val,resList,path);
            path.remove(path.size() - 1); //回溯
        }
    }

總結:帶了點回溯

相關文章