利用前序遍歷和中序遍歷構造二叉樹


根據一棵樹的前序遍歷與中序遍歷構造二叉樹。 注意: 你可以假設樹中沒有重復的元素。 例如,給出 前序遍歷 preorder = [3,9,20,15,7] 中序遍歷 inorder = [9,3,15,20,7] 返回如下的二叉樹: 3
    / \ 9  20
     / \ 15   7

思想:利用分治的思想來解決該題

具體解題步驟:

  1.根據先序遍歷,我們可以知道根節點就是給定數組的第一個元素pre[0],那么我們就可以在中序遍歷中找出值等於pre[0]的位置,該位置的前半部分就是左子樹,右半部分就是右子樹,

  2.重復1,直到遍歷完

實現代碼如下:

public class Solution { public int preIndex = 0;
//查找pre[pri]的位置 public int find(int[] inorder, int inbegin,int inend,int val){ for(int i = inbegin;i<=inend;i++){ if(inorder[i] == val) return i; } return -1; }
public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin,int inend) { if(inbegin>inend) return null; TreeNode root = new TreeNode(preorder[preIndex]); int index = find(inorder,inbegin,inend,preorder[preIndex]); if(index == -1) return null; preIndex++; root.left = buildTreeChild(preorder,inorder,inbegin,index-1); root.right = buildTreeChild(preorder,inorder,index+1,inend); return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null) return null; return buildTreeChild(preorder,inorder,0,inorder.length-1); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM