本节内容
513.找树左下角的值
112. 路径总和 113.路径总和ii
106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树
513. 找树左下角的值※ 建议 :本地递归偏难,反而迭代简单属于模板题, 两种方法掌握一下
题目链接: https://leetcode.cn/problems/find-bottom-left-tree-value/ 文章讲解: https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html
题目分析
递归遍历 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution { public int findBottomLeftValue (TreeNode root) { return recursion(root, 0 )[0 ]; } private int [] recursion(TreeNode root, int depth) { depth++; if (root == null ) return new int []{0 ,-1 , depth}; int [] recursionLeft = recursion(root.left, depth); int [] recursionRight = recursion(root.right, depth); if (recursionLeft[2 ] < recursionRight[2 ]) { return recursionRight; } else { if (recursionLeft[1 ] == -1 ) { recursionLeft[0 ] = root.val; recursionLeft[1 ] = 1 ; } return recursionLeft; } } }
结果 解答成功: 执行耗时:0 ms,击败了100.00% 的Java用户 内存消耗:42.5 MB,击败了62.54% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( log n )
迭代遍历(层序遍历) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public int findBottomLeftValue (TreeNode root) { Deque<TreeNode> queue = new LinkedList <>(); int result = root.val; queue.offer(root); while (!queue.isEmpty()) { queue.offer(null ); result = queue.peek().val; while (queue.peek() != null ) { TreeNode poll = queue.poll(); if (poll.left != null ) queue.offer(poll.left); if (poll.right != null ) queue.offer(poll.right); } queue.poll(); } return result; } }
结果 解答成功: 执行耗时:2 ms,击败了15.79% 的Java用户 内存消耗:42.6 MB,击败了56.35% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( n )
代码随想录 https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html
递归 咋眼一看,这道题目用递归的话就就一直向左遍历,最后一个就是答案呗?
没有这么简单,一直向左遍历到最后一个,它未必是最后一行啊。
我们来分析一下题目:在树的最后一行 找到最左边的值 。
首先要是最后一行,然后是最左边的值。
如果使用递归法,如何判断是最后一行呢,其实就是深度最大的叶子节点一定是最后一行。
所以要找深度最大的叶子节点。
那么如何找最左边的呢?可以使用前序遍历(当然中序,后序都可以,因为本题没有 中间节点的处理逻辑,只要左优先就行),保证优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值。
递归三部曲:
确定递归函数的参数和返回值
参数必须有要遍历的树的根节点,还有就是一个int型的变量用来记录最长深度。 这里就不需要返回值了,所以递归函数的返回类型为void。
本题还需要类里的两个全局变量,maxLen用来记录最大深度,result记录最大深度最左节点的数值。
代码如下:
1 2 3 int maxDepth = INT_MIN; int result; void traversal (TreeNode* root, int depth)
确定终止条件
当遇到叶子节点的时候,就需要统计一下最大的深度了,所以需要遇到叶子节点来更新最大深度。
代码如下:
1 2 3 4 5 6 7 if (root->left == NULL && root->right == NULL ) { if (depth > maxDepth) { maxDepth = depth; result = root->val; } return ; }
确定单层递归的逻辑
在找最大深度的时候,递归的过程中依然要使用回溯,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 if (root->left) { depth++; traversal (root->left, depth); depth--; }if (root->right) { depth++; traversal (root->right, depth); depth--; }return ;
代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution { private int Deep = -1 ; private int value = 0 ; public int findBottomLeftValue (TreeNode root) { value = root.val; findLeftValue(root,0 ); return value; } private void findLeftValue (TreeNode root,int deep) { if (root == null ) return ; if (root.left == null && root.right == null ) { if (deep > Deep) { value = root.val; Deep = deep; } } if (root.left != null ) findLeftValue(root.left,deep + 1 ); if (root.right != null ) findLeftValue(root.right,deep + 1 ); } }
迭代法 https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html#%E8%BF%AD%E4%BB%A3%E6%B3%95
本题使用层序遍历再合适不过了,比递归要好理解得多!
只需要记录最后一行第一个节点的数值就可以了。
代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public int findBottomLeftValue (TreeNode root) { Queue<TreeNode> queue = new LinkedList <>(); queue.offer(root); int res = 0 ; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0 ; i < size; i++) { TreeNode poll = queue.poll(); if (i == 0 ) { res = poll.val; } if (poll.left != null ) { queue.offer(poll.left); } if (poll.right != null ) { queue.offer(poll.right); } } } return res; } }
112. 路径总和※ 建议 :本题 又一次设计要回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解
\112. 路径总和,和 113. 路径总和ii 一起做了。 优先掌握递归法。
题目链接: https://leetcode.cn/problems/path-sum/ 文章讲解: https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html
题目分析
递归遍历 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { private boolean FLAG = false ; public boolean hasPathSum (TreeNode root, int targetSum) { if (root == null ) return false ; recursion(root, targetSum, 0 ); return FLAG; } private void recursion (TreeNode root, int targetSum, int sum) { if (root.left == null && root.right == null ) { sum = sum + root.val; if (targetSum == sum) { FLAG = true ; } return ; } if (root.left != null ){ recursion(root.left, targetSum, sum + root.val); } if (root.right != null ){ recursion(root.right, targetSum, sum + root.val); } } }
结果 解答成功: 执行耗时:0 ms,击败了100.00% 的Java用户 内存消耗:42.2 MB,击败了48.02% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( log n )
迭代遍历 看了代码随想录的相关内容,才想起来使用两个栈来存储数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Solution { public boolean hasPathSum (TreeNode root, int targetSum) { if (root == null ) return false ; Deque<TreeNode> stack = new LinkedList <>(); Deque<Integer> sumInt = new LinkedList <>(); int sum = 0 ; stack.push(root); sumInt.push(0 ); while (!stack.isEmpty()) { TreeNode pop = stack.pop(); sum = sumInt.pop() + pop.val; if (pop.left == null && pop.right == null && sum == targetSum) { return true ; } if (pop.right != null ) { stack.push(pop.right); sumInt.push(sum); } if (pop.left != null ) { stack.push(pop.left); sumInt.push(sum); } } return false ; } }
结果 解答成功: 执行耗时:2 ms,击败了8.12% 的Java用户 内存消耗:42.2 MB,击败了45.33% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( n )
代码随想录 https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html
递归 可以使用深度优先遍历的方式(本题前中后序都可以,无所谓,因为中节点也没有处理逻辑)来遍历二叉树
确定递归函数的参数和返回类型
参数:需要二叉树的根节点,还需要一个计数器,这个计数器用来计算二叉树的一条边之和是否正好是目标和,计数器为int型。
再来看返回值,递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:
如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。
如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。
如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)
而本题我们要找一条符合条件的路径,所以递归函数需要返回值,及时返回,那么返回类型是什么呢?
如图所示:
图中可以看出,遍历的路线,并不要遍历整棵树,所以递归函数需要返回值,可以用bool类型表示。
所以代码如下:
1 bool traversal (treenode* cur, int count)
确定终止条件
首先计数器如何统计这一条路径的和呢?
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
如果最后count == 0,同时到了叶子节点的话,说明找到了目标和。
如果遍历到了叶子节点,count不为0,就是没找到。
递归终止条件代码如下:
1 2 if (!cur->left && !cur->right && count == 0 ) return true ; if (!cur->left && !cur->right) return false ;
确定单层递归的逻辑
因为终止条件是判断叶子节点,所以递归的过程中就不要让空节点进入递归了。
递归函数是有返回值的,如果递归函数返回true,说明找到了合适的路径,应该立刻返回。
代码如下:
1 2 3 4 5 6 7 8 9 if (cur->left) { if (traversal (cur->left, count - cur->left->val)) return true ; }if (cur->right) { if (traversal (cur->right, count - cur->right->val)) return true ; }return false ;
以上代码中是包含着回溯的,没有回溯,如何后撤重新找另一条路径呢。
回溯隐藏在traversal(cur->left, count - cur->left->val)
这里, 因为把count - cur->left->val
直接作为参数传进去,函数结束,count的数值没有改变。
为了把回溯的过程体现出来,可以改为如下代码:
1 2 3 4 5 6 7 8 9 10 11 if (cur->left) { count -= cur->left->val; if (traversal (cur->left, count)) return true ; count += cur->left->val; }if (cur->right) { count -= cur->right->val; if (traversal (cur->right, count)) return true ; count += cur->right->val; }return false ;
代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 class solution { public boolean haspathsum (treenode root, int targetsum) { if (root == null ) { return false ; } targetsum -= root.val; if (root.left == null && root.right == null ) { return targetsum == 0 ; } if (root.left != null ) { boolean left = haspathsum(root.left, targetsum); if (left) { return true ; } } if (root.right != null ) { boolean right = haspathsum(root.right, targetsum); if (right) { return true ; } } return false ; } }class solution { public boolean haspathsum (treenode root, int targetsum) { if (root == null ) return false ; if (root.left == null && root.right == null ) return root.val == targetsum; return haspathsum(root.left, targetsum - root.val) || haspathsum(root.right, targetsum - root.val); } }
迭代 https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html#%E8%BF%AD%E4%BB%A3
如果使用栈模拟递归的话,那么如果做回溯呢?
此时栈里一个元素不仅要记录该节点指针,还要记录从头结点到该节点的路径数值总和。
代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class solution { public boolean haspathsum (treenode root, int targetsum) { if (root == null ) return false ; stack<treenode> stack1 = new stack <>(); stack<integer> stack2 = new stack <>(); stack1.push(root); stack2.push(root.val); while (!stack1.isempty()) { int size = stack1.size(); for (int i = 0 ; i < size; i++) { treenode node = stack1.pop(); int sum = stack2.pop(); if (node.left == null && node.right == null && sum == targetsum) { return true ; } if (node.right != null ){ stack1.push(node.right); stack2.push(sum + node.right.val); } if (node.left != null ) { stack1.push(node.left); stack2.push(sum + node.left.val); } } } return false ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public boolean hasPathSum (TreeNode root, int targetSum) { Stack<TreeNode> treeNodeStack = new Stack <>(); Stack<Integer> sumStack = new Stack <>(); if (root == null ) return false ; treeNodeStack.add(root); sumStack.add(root.val); while (!treeNodeStack.isEmpty()){ TreeNode curr = treeNodeStack.peek(); int tempsum = sumStack.pop(); if (curr != null ){ treeNodeStack.pop(); treeNodeStack.add(curr); treeNodeStack.add(null ); sumStack.add(tempsum); if (curr.right != null ){ treeNodeStack.add(curr.right); sumStack.add(tempsum + curr.right.val); } if (curr.left != null ){ treeNodeStack.add(curr.left); sumStack.add(tempsum + curr.left.val); } }else { treeNodeStack.pop(); TreeNode temp = treeNodeStack.pop(); if (temp.left == null && temp.right == null && tempsum == targetSum) return true ; } } return false ; }
113. 路径总和 II
官方题目链接: 113. 路径总和 II
题目分析
递归 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Solution { public List<List<Integer>> pathSum (TreeNode root, int targetSum) { List<List<Integer>> result = new ArrayList <>(); if (root == null ) return result; recursion(root, targetSum, 0 , new ArrayList <>(), result); return result; } private void recursion (TreeNode root, int targetSum, int sum, List<Integer> path, List<List<Integer>> result) { if (root.left == null && root.right == null ) { sum += root.val; path.add(root.val); if (sum == targetSum){ result.add(new ArrayList <>(path)); } sum -= root.val; path.remove(path.size() - 1 ); return ; } path.add(root.val); if (root.left != null ){ recursion(root.left, targetSum, sum + root.val, path, result); } if (root.right != null ){ recursion(root.right, targetSum, sum + root.val, path, result); } path.remove(path.size() - 1 ); } }
结果 解答成功: 执行耗时:1 ms,击败了99.89% 的Java用户 内存消耗:42.8 MB,击败了42.17% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( log n )
迭代 使用了三个栈结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class Solution { public List<List<Integer>> pathSum (TreeNode root, int targetSum) { List<List<Integer>> result = new ArrayList <>(); if (root == null ) return result; Deque<TreeNode> stack = new LinkedList <>(); Deque<List<Integer>> listStack = new LinkedList <>(); Deque<Integer> sumStack = new LinkedList <>(); stack.push(root); sumStack.push(0 ); listStack.push(new ArrayList <>()); while (!stack.isEmpty()) { TreeNode pop = stack.pop(); List<Integer> list = listStack.pop(); list.add(pop.val); Integer sum = sumStack.pop() + pop.val; if (sum == targetSum && pop.left == null && pop.right == null ) { result.add(new ArrayList <>(list)); } if (pop.right != null ){ stack.push(pop.right); sumStack.push(sum); listStack.push(new ArrayList <>(list)); } if (pop.left != null ){ stack.push(pop.left); sumStack.push(sum); listStack.push(new ArrayList <>(list)); } } return result; } }
结果 解答成功: 执行耗时:3 ms,击败了7.46% 的Java用户 内存消耗:43.4 MB,击败了7.09% 的Java用户
分析 时间复杂度: O( n )
空间复杂度: O( n )
代码随想录 https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html#%E7%9B%B8%E5%85%B3%E9%A2%98%E7%9B%AE%E6%8E%A8%E8%8D%90
113.路径总和ii要遍历整个树,找到所有路径,所以递归函数不要返回值!
如图:
代码实现 递归法一 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class solution { public List<List<Integer>> pathsum (TreeNode root, int targetsum) { List<List<Integer>> res = new ArrayList <>(); if (root == null ) return res; List<Integer> path = new LinkedList <>(); preorderdfs(root, targetsum, res, path); return res; } public void preorderdfs (TreeNode root, int targetsum, List<List<Integer>> res, List<Integer> path) { path.add(root.val); if (root.left == null && root.right == null ) { if (targetsum - root.val == 0 ) { res.add(new ArrayList <>(path)); } return ; } 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 ); } } }
递归法二 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution { List<List<Integer>> result; LinkedList<Integer> path; public List<List<Integer>> pathSum (TreeNode root,int targetSum) { result = new LinkedList <>(); path = new LinkedList <>(); travesal(root, targetSum); return result; } private void travesal (TreeNode root, int count) { if (root == null ) return ; path.offer(root.val); count -= root.val; if (root.left == null && root.right == null && count == 0 ) { result.add(new LinkedList <>(path)); } travesal(root.left, count); travesal(root.right, count); path.removeLast(); } }
迭代法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class Solution { public List<List<Integer>> pathSum (TreeNode root, int targetSum) { List<List<Integer>> result = new ArrayList <>(); Stack<TreeNode> nodeStack = new Stack <>(); Stack<Integer> sumStack = new Stack <>(); Stack<ArrayList<Integer>> pathStack = new Stack <>(); if (root == null ) return result; nodeStack.add(root); sumStack.add(root.val); pathStack.add(new ArrayList <>()); while (!nodeStack.isEmpty()){ TreeNode currNode = nodeStack.peek(); int currSum = sumStack.pop(); ArrayList<Integer> currPath = pathStack.pop(); if (currNode != null ){ nodeStack.pop(); nodeStack.add(currNode); nodeStack.add(null ); sumStack.add(currSum); currPath.add(currNode.val); pathStack.add(new ArrayList (currPath)); if (currNode.right != null ){ nodeStack.add(currNode.right); sumStack.add(currSum + currNode.right.val); pathStack.add(new ArrayList (currPath)); } if (currNode.left != null ){ nodeStack.add(currNode.left); sumStack.add(currSum + currNode.left.val); pathStack.add(new ArrayList (currPath)); } }else { nodeStack.pop(); TreeNode temp = nodeStack.pop(); if (temp.left == null && temp.right == null && currSum == targetSum) result.add(new ArrayList (currPath)); } } return result; } }
106.从中序与后序遍历序列构造二叉树※ 建议 :本题 又一次设计要回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解
106.从中序与后序遍历序列构造二叉树,105.从前序与中序遍历序列构造二叉树 一起做,思路一样的
题目链接: https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 文章讲解: https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html
题目分析
方案一 似乎自行解决了此问题,但是问题解决的过程比较困难 首先是审题的时候,被卡住,发现没用思路,看来一眼题解的思路才找到如何去做 做的过程中,对于很多的细节没用掌握到,导致程序报 索引越界 堆栈溢出的错误。 最终再不懈努力下,成功AC。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Solution { public TreeNode buildTree (int [] inorder, int [] postorder) { return recursion(inorder, 0 , inorder.length - 1 , postorder, 0 , postorder.length - 1 ); } private TreeNode recursion (int [] inorder, int inStart, int inEnd, int [] postorder, int poStart, int poEnd) { if (inEnd < inStart) return null ; TreeNode head = new TreeNode (); int i = postorder[poEnd]; head.val = i; int index = findIndex(inorder, i, inStart, inEnd); TreeNode leftRecursion = recursion(inorder, inStart, (index - 1 ), postorder, poStart, (poStart + index - inStart - 1 )); TreeNode rightRecursion = recursion(inorder,(index + 1 ), inEnd, postorder, (poStart + index - inStart), poEnd - 1 ); head.left = leftRecursion; head.right = rightRecursion; return head; } private int findIndex (int [] list, int target, int start, int end) { for (int i = start; i <= end; i++) { if (list[i] == target) return i; } return -1 ; } }
结果 解答成功: 执行耗时:3 ms,击败了40.76% 的Java用户 内存消耗:42.4 MB,击败了22.59% 的Java用户
代码随想录 https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html
思路 首先回忆一下如何根据两个顺序构造一个唯一的二叉树,相信理论知识大家应该都清楚,就是以 后序数组的最后一个元素为切割点,先切中序数组,根据中序数组,反过来再切后序数组。一层一层切下去,每次后序数组最后一个元素就是节点元素。
如果让我们肉眼看两个序列,画一棵二叉树的话,应该分分钟都可以画出来。
流程如图:
那么代码应该怎么写呢?
说到一层一层切割,就应该想到了递归。
来看一下一共分几步:
第一步:如果数组大小为零的话,说明是空节点了。
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
第五步:切割后序数组,切成后序左数组和后序右数组
第六步:递归处理左区间和右区间
不难写出如下代码:(先把框架写出来)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 TreeNode* traversal (vector<int >& inorder, vector<int >& postorder) { if (postorder.size () == 0 ) return NULL ; int rootValue = postorder[postorder.size () - 1 ]; TreeNode* root = new TreeNode (rootValue); if (postorder.size () == 1 ) return root; int delimiterIndex; for (delimiterIndex = 0 ; delimiterIndex < inorder.size (); delimiterIndex++) { if (inorder[delimiterIndex] == rootValue) break ; } root->left = traversal (中序左数组, 后序左数组); root->right = traversal (中序右数组, 后序右数组); return root; }
难点大家应该发现了,就是如何切割,以及边界值找不好很容易乱套。
此时应该注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量。
在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭右闭,必然乱套!
首先要切割中序数组,为什么先切割中序数组呢?
切割点在后序数组的最后一个元素,就是用这个元素来切割中序数组的,所以必要先切割中序数组。
中序数组相对比较好切,找到切割点(后序数组的最后一个元素)在中序数组的位置,然后切割,如下代码中我坚持左闭右开的原则:
1 2 3 4 5 6 7 8 9 10 int delimiterIndex;for (delimiterIndex = 0 ; delimiterIndex < inorder.size (); delimiterIndex++) { if (inorder[delimiterIndex] == rootValue) break ; }vector<int > leftInorder (inorder.begin(), inorder.begin() + delimiterIndex) ;vector<int > rightInorder (inorder.begin() + delimiterIndex + 1 , inorder.end() ) ;
接下来就要切割后序数组了。
首先后序数组的最后一个元素指定不能要了,这是切割点 也是 当前二叉树中间节点的元素,已经用了。
后序数组的切割点怎么找?
后序数组没有明确的切割元素来进行左右切割,不像中序数组有明确的切割点,切割点左右分开就可以了。
此时有一个很重的点,就是中序数组大小一定是和后序数组的大小相同的(这是必然)。
中序数组我们都切成了左中序数组和右中序数组了,那么后序数组就可以按照左中序数组的大小来切割,切成左后序数组和右后序数组。
代码如下:
1 2 3 4 5 6 7 postorder.resize (postorder.size () - 1 );vector<int > leftPostorder (postorder.begin(), postorder.begin() + leftInorder.size()) ;vector<int > rightPostorder (postorder.begin() + leftInorder.size(), postorder.end()) ;
此时,中序数组切成了左中序数组和右中序数组,后序数组切割成左后序数组和右后序数组。
接下来可以递归了,代码如下:
1 2 root->left = traversal (leftInorder, leftPostorder); root->right = traversal (rightInorder, rightPostorder);
代码实现 代码实现与方案一类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { Map<Integer, Integer> map; public TreeNode buildTree (int [] inorder, int [] postorder) { map = new HashMap <>(); for (int i = 0 ; i < inorder.length; i++) { map.put(inorder[i], i); } return findNode(inorder, 0 , inorder.length, postorder,0 , postorder.length); } public TreeNode findNode (int [] inorder, int inBegin, int inEnd, int [] postorder, int postBegin, int postEnd) { if (inBegin >= inEnd || postBegin >= postEnd) { return null ; } int rootIndex = map.get(postorder[postEnd - 1 ]); TreeNode root = new TreeNode (inorder[rootIndex]); int lenOfLeft = rootIndex - inBegin; root.left = findNode(inorder, inBegin, rootIndex, postorder, postBegin, postBegin + lenOfLeft); root.right = findNode(inorder, rootIndex + 1 , inEnd, postorder, postBegin + lenOfLeft, postEnd - 1 ); return root; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public TreeNode buildTree (int [] inorder, int [] postorder) { if (postorder.length == 0 || inorder.length == 0 ) return null ; return buildHelper(inorder, 0 , inorder.length, postorder, 0 , postorder.length); } private TreeNode buildHelper (int [] inorder, int inorderStart, int inorderEnd, int [] postorder, int postorderStart, int postorderEnd) { if (postorderStart == postorderEnd) return null ; int rootVal = postorder[postorderEnd - 1 ]; TreeNode root = new TreeNode (rootVal); int middleIndex; for (middleIndex = inorderStart; middleIndex < inorderEnd; middleIndex++){ if (inorder[middleIndex] == rootVal) break ; } int leftInorderStart = inorderStart; int leftInorderEnd = middleIndex; int rightInorderStart = middleIndex + 1 ; int rightInorderEnd = inorderEnd; int leftPostorderStart = postorderStart; int leftPostorderEnd = postorderStart + (middleIndex - inorderStart); int rightPostorderStart = leftPostorderEnd; int rightPostorderEnd = postorderEnd - 1 ; root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart, leftPostorderEnd); root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart, rightPostorderEnd); return root; } }
105. 从前序与中序遍历序列构造二叉树
官方题目链接: 105. 从前序与中序遍历序列构造二叉树
题目分析
方案一 与上一题极其类似,或者可以说一模一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution { public TreeNode buildTree (int [] preorder, int [] inorder) { return recursion(preorder, 0 , preorder.length - 1 , inorder, 0 , inorder.length - 1 ); } private TreeNode recursion (int [] preorder, int prStart, int prEnd, int [] inorder, int inStart, int inEnd) { if (prStart > prEnd) return null ; TreeNode head = new TreeNode (preorder[prStart]); int index = findIndex(inorder, preorder[prStart], inStart, inEnd); head.left = recursion(preorder, prStart + 1 , prStart + index - inStart, inorder, inStart, index - 1 ); head.right = recursion(preorder, prStart + index - inStart + 1 , prEnd, inorder, index + 1 , inEnd); return head; } private int findIndex (int [] list, int target, int start, int end) { for (int i = start; i <= end; i++) { if (list[i] == target) return i; } return -1 ; } }
结果 解答成功: 执行耗时:3 ms,击败了42.65% 的Java用户 内存消耗:42 MB,击败了61.91% 的Java用户
代码随想录 https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E7%9B%B8%E5%85%B3%E9%A2%98%E7%9B%AE%E6%8E%A8%E8%8D%90
本题和106是一样的道理。
代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { Map<Integer, Integer> map; public TreeNode buildTree (int [] preorder, int [] inorder) { map = new HashMap <>(); for (int i = 0 ; i < inorder.length; i++) { map.put(inorder[i], i); } return findNode(preorder, 0 , preorder.length, inorder, 0 , inorder.length); } public TreeNode findNode (int [] preorder, int preBegin, int preEnd, int [] inorder, int inBegin, int inEnd) { if (preBegin >= preEnd || inBegin >= inEnd) { return null ; } int rootIndex = map.get(preorder[preBegin]); TreeNode root = new TreeNode (inorder[rootIndex]); int lenOfLeft = rootIndex - inBegin; root.left = findNode(preorder, preBegin + 1 , preBegin + lenOfLeft + 1 , inorder, inBegin, rootIndex); root.right = findNode(preorder, preBegin + lenOfLeft + 1 , preEnd, inorder, rootIndex + 1 , inEnd); return root; } }