diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 49e7f828..ba2d46a1 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 ## 其他语言版本 - Java: + +106.从中序与后序遍历序列构造二叉树 + ```java class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { @@ -617,8 +619,43 @@ class Solution { } ``` +105.从前序与中序遍历序列构造二叉树 + +```java +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); + } + + public TreeNode helper(int[] preorder, int preLeft, int preRight, + int[] inorder, int inLeft, int inRight) { + // 递归终止条件 + if (inLeft > inRight || preLeft > preRight) return null; + + // val 为前序遍历第一个的值,也即是根节点的值 + // idx 为根据根节点的值来找中序遍历的下标 + int idx = inLeft, val = preorder[preLeft]; + TreeNode root = new TreeNode(val); + for (int i = inLeft; i <= inRight; i++) { + if (inorder[i] == val) { + idx = i; + break; + } + } + + // 根据 idx 来递归找左右子树 + root.left = helper(preorder, preLeft + 1, preLeft + (idx - inLeft), + inorder, inLeft, idx - 1); + root.right = helper(preorder, preLeft + (idx - inLeft) + 1, preRight, + inorder, idx + 1, inRight); + return root; + } +} +``` + Python: 105.从前序与中序遍历序列构造二叉树 + ```python # Definition for a binary tree node. # class TreeNode: @@ -637,6 +674,7 @@ class Solution: return root ``` 106.从中序与后序遍历序列构造二叉树 + ```python # Definition for a binary tree node. # class TreeNode: diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 65f0fa62..b4a3f38b 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -347,6 +347,42 @@ class Solution { } ``` +0113.路径总和-ii + +```java +class Solution { + public List> pathSum(TreeNode root, int targetSum) { + List> res = new ArrayList<>(); + if (root == null) return res; // 非空判断 + + List path = new LinkedList<>(); + preorderDFS(root, targetSum, res, path); + return res; + } + + public void preorderDFS(TreeNode root, int targetSum, List> res, List path) { + path.add(root.val); + // 遇到了叶子节点 + if (root.left == null && root.right == null) { + // 找到了和为 targetSum 的路径 + if (targetSum - root.val == 0) { + res.add(new ArrayList<>(path)); + } + return; // 如果和不为 targetSum,返回 + } + + if (root.left != null) { + preorderDFS(root.left, targetSum - root.val, res, path); + path.remove(path.size() - 1); // 回溯 + } + if (root.right != null) { + preorderDFS(root.right, targetSum - root.val, res, path); + path.remove(path.size() - 1); // 回溯 + } + } +} +``` + Python: 0112.路径总和