diff --git a/notes/剑指 offer 题解.md b/notes/剑指 offer 题解.md index dcd92668..156b86a5 100644 --- a/notes/剑指 offer 题解.md +++ b/notes/剑指 offer 题解.md @@ -254,16 +254,16 @@ public ArrayList printListFromTailToHead(ListNode listNode) { public TreeNode reConstructBinaryTree(int[] pre, int[] in) { return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1); } + private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int[] in, int inL, int inR) { - if(preL > preR || inL > inR) return null; + if (preL == preR) return new TreeNode(pre[preL]); + if (preL > preR || inL > inR) return null; TreeNode root = new TreeNode(pre[preL]); - if (preL != preR) { - int idx = inL; - while (idx <= inR && in[idx] != root.val) idx++; - int leftTreeLen = idx - inL; - root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeLen, in, inL, inL + leftTreeLen - 1); - root.right = reConstructBinaryTree(pre, preL + leftTreeLen + 1, preR, in, inL + leftTreeLen + 1, inR); - } + int midIdx = inL; + while (midIdx <= inR && in[midIdx] != root.val) midIdx++; + int leftTreeSize = midIdx - inL; + root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, in, inL, inL + leftTreeSize - 1); + root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, in, inL + leftTreeSize + 1, inR); return root; } ``` @@ -274,6 +274,13 @@ private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int[] in, ¸ø¶¨Ò»¸ö¶þ²æÊ÷ºÍÆäÖеÄÒ»¸ö½áµã£¬ÇëÕÒ³öÖÐÐò±éÀú˳ÐòµÄÏÂÒ»¸ö½áµã²¢ÇÒ·µ»Ø¡£×¢Ò⣬Ê÷ÖеĽáµã²»½ö°üº¬×óÓÒ×Ó½áµã£¬Í¬Ê±°üº¬Ö¸Ïò¸¸½áµãµÄÖ¸Õë¡£ +**½âÌâ˼·** + +- Èç¹ûÒ»¸ö½ÚµãÓÐÓÒ×ÓÊ÷²»Îª¿Õ£¬ÄÇô¸Ã½ÚµãµÄÏÂÒ»¸ö½ÚµãÊÇÓÒ×ÓÊ÷µÄ×î×ó½Úµã£» +- ·ñÔò£¬ÏòÉÏÕÒµÚÒ»¸ö×óÁ´½ÓÖ¸ÏòµÄÊ÷°üº¬¸Ã½ÚµãµÄ×æÏȽڵ㡣 + +![](https://github.com/CyC2018/InterviewNotes/blob/master/pics/6fec7f56-a685-4232-b03e-c92a8dfba486.png) + ```java public TreeLinkNode GetNext(TreeLinkNode pNode) { if (pNode == null) return null; diff --git a/pics/6fec7f56-a685-4232-b03e-c92a8dfba486.png b/pics/6fec7f56-a685-4232-b03e-c92a8dfba486.png new file mode 100644 index 00000000..b627cea5 Binary files /dev/null and b/pics/6fec7f56-a685-4232-b03e-c92a8dfba486.png differ