[Leetcode][第106题][JAVA][ 从中序与后序遍历序列构造二叉树][分治][递归]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第106题][JAVA][ 从中序与后序遍历序列构造二叉树][分治][递归]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
HashMap優化
copyOfRange 左必右開
class Solution {public TreeNode buildTree(int[] inorder, int[] postorder) {if(inorder==null || postorder==null) {return null;}return helper(inorder,postorder);}private TreeNode helper(int[] in, int[] post) {if(in.length==0) {return null;}//根據后序數組的最后一個元素,創建根節點TreeNode root = new TreeNode(post[post.length-1]);//在中序數組中查找值等于【后序數組最后一個元素】的下標for(int i=0;i<in.length;++i) {if(in[i]==post[post.length-1]) {//確定這個下標i后,將中序數組分成兩部分,后序數組分成兩部分int[] inLeft = Arrays.copyOfRange(in,0,i);int[] inRight = Arrays.copyOfRange(in,i+1,in.length);int[] postLeft = Arrays.copyOfRange(post,0,i);int[] postRight = Arrays.copyOfRange(post,i,post.length-1);//遞歸處理中序數組左邊,后序數組左邊root.left = helper(inLeft,postLeft);//遞歸處理中序數組右邊,后序數組右邊root.right = helper(inRight,postRight);break;}}return root;} }作者:wang_ni_ma 鏈接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/liang-chong-shi-xian-dong-hua-yan-shi-106-cong-zho/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。【總結】
1.前中后序遍歷變化的是[中]的位置,左到右的順序不改變
- 前序遍歷 中左右
- 中序遍歷 左中右
- 后續遍歷 左右中
2.還原二叉樹 借助HashMap or copyOfRange
根據前序和后序遍歷構造二叉樹
[Leetcode][第889題][JAVA][根據前序和后序遍歷構造二叉樹][分治][遞歸]
前序+中序遍歷可畫出原二叉樹
[Leedcode][JAVA][第105題][從前序與中序遍歷序列構造二叉樹][棧][遞歸][二叉樹]
后續+中序遍歷可畫出原二叉樹
[Leetcode][第106題][JAVA][ 從中序與后序遍歷序列構造二叉樹][分治][遞歸]
3. 多畫圖 寫寫寫 遍歷代碼 手撕變量 大腦保持清醒
轉載鏈接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/hou-xu-bian-li-python-dai-ma-java-dai-ma-by-liwe-2/
轉載鏈接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/tu-jie-gou-zao-er-cha-shu-wei-wan-dai-xu-by-user72/
總結
以上是生活随笔為你收集整理的[Leetcode][第106题][JAVA][ 从中序与后序遍历序列构造二叉树][分治][递归]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DP备份任务失败原因解析
- 下一篇: tcp keeplive