二叉树、回溯、序列化

190 阅读1分钟

二叉树与DFS、回溯

113. 路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

img

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 
输出:[[5,4,11,2],[5,8,4,5]]
 class Solution {
 ​
     List<List<Integer>> res = new ArrayList<>();
 ​
     public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
         helper(root, targetSum, new ArrayList<Integer>());
         return res;
     }
 ​
 ​
     public void helper(TreeNode root, int targetSum, List<Integer> list) {
         if (root == null) {
             return;
         }
         list.add(root.val);
         targetSum = targetSum - root.val;
         if (root.left == null && root.right == null) {
             if (targetSum == 0) {
                 res.add(new ArrayList<>(list));
                 list.remove(list.size()-1);
                 targetSum = targetSum + root.val;
                 return;
             }
         }
         helper(root.left, targetSum, list);
         helper(root.right, targetSum, list);
         list.remove(list.size()-1);
         targetSum = targetSum + root.val;
     }
 }

二叉树与序列化

652. Find Duplicate Subtrees

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

Example 1:

img

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
 class Solution {
     
     private List<TreeNode> res;
     
     public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
         res = new ArrayList<>();
         helper(root, new HashMap<String, Integer>());
         return res;
     }
     
     public String helper(TreeNode root, Map<String, Integer> map) {
         if (root == null) return "#";
         String left = helper(root.left, map);
         String right = helper(root.right, map);
         String now = root.val +"," + left + "," + right;
         map.put(now, map.getOrDefault(now, 0) + 1);
         if (map.get(now) == 2) {
             res.add(root);
         }
         return now;
     }
     
 }

\