Leetcode 889 根据前序和后序遍历构造二叉树 区间递归
前序遍历与后续遍历的组合可以构成一个完整的子树区间。
子树的根节点会在前序遍历中该子树的首位出现,在后续遍历中则会在该子树的末尾出现。
那么,前序-后序的重合节点所构成的区间,便是以该重合节点为根节点的整棵子树。
进而考虑该思路是否可以一直递归至边界情况。
JAVA:
public final TreeNode constructFromPrePost(int[] pre, int[] post) { int childLen = 0, preLen = pre.length, postLen = post.length; if (preLen == 0) return null; TreeNode root = new TreeNode(pre[0]); if (preLen == 1) return root; for (int i = 0; i < postLen; i++) { if (post[i] == pre[1]) { childLen = i; break; } } root.left = constructFromPrePost( Arrays.copyOfRange(pre, 1, childLen + 2), Arrays.copyOfRange(post, 0, childLen+1) ); root.right = constructFromPrePost( Arrays.copyOfRange(pre, childLen + 2, preLen), Arrays.copyOfRange(post, childLen + 1, postLen - 1) ); return root; }
JS:
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {number[]} pre * @param {number[]} post * @return {TreeNode} */ var constructFromPrePost = function (pre, post) { let childLen = 0, preLen = pre.length, postLen = post.length; if (preLen == 0) return null; let root = new TreeNode(pre[0]); if (preLen == 1) return root; for (let i = 0; i < postLen; i++) { if (post[i] == pre[1]) { childLen = i; break; } } root.left = constructFromPrePost(pre.slice(1, childLen + 2), post.slice(0, childLen + 1)); root.right = constructFromPrePost(pre.slice(childLen + 2, preLen), post.slice(childLen + 1, postLen - 1)); return root; };
当你看清人们的真相,于是你知道了,你可以忍受孤独