二叉树前序中序后序_从前序、中序、后序序列构造二叉树

6eb872f47c875baa5ddabda57002eace.png

??根据一棵树的中序遍历与后序遍历构造二叉树(LeetCode-106)。
      ?注意:你可以假设树中没有重复的元素。

?例如,给出   

中序遍历 inorder = [9,3,15,20,7]

后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

            3      

           / \      

          9  20 

            /  \    

          15   7 

?递归解法:

?思路:

        右序序列的右边界值一定为root节点,左边界值一定为最左节点。

        用一个常量postInx表示后序序列的下标,初始化值为postorder.length-1每递归一次减1。

        用一个Map来存放中序序列:key=node_val,value=index。

       采用递归hepler(int left_index,int right_index),两个参数分别为中序序列中当前子树的左右边界值。

int postInx;int[] postOrderArray;HashMap map =new HashMap<>();public TreeNode buildTree(int[] inOrderArray, int[] postOrderArray) {  this.postInx = postOrderArray.length -1;  this.postOrderArray = postOrderArray;  for (int i = 0; i < inOrderArray.length; i++) {      map.put(inOrderArray[i], i);  }  return helper(0, inOrderArray.length - 1);    }private TreeNode helper(int in_left, int in_right) {  if (in_left > in_right) {      return null;  }  int node_val = postOrderArray[postInx];  TreeNode root = new TreeNode(node_val);  int inx = map.get(node_val);  postInx--;  root.right = helper(inx + 1, in_right);  root.left = helper(in_left, inx - 1);  return root;}
??根据一棵树的中序遍历与后序遍历构造二叉树(LeetCode-105)。
      ?注意:你可以假设树中没有重复的元素。

?例如,给出   

中序遍历 inorder = [4,2,1,5,3,6]

后序遍历 postorder = [,12,4,3,5,6]

返回如下的二叉树:

             1       

            / \      

          2  3     

          /   /  \   

        4  5   6  

?递归解法:

?思路:

        和LeetCode-106思路差不多,前序序列的第一个元素一定是树的根节点,用一个常量preInx来表示前序遍历的序列下标,每递归一次加1。

        用一个Map来存放中序序列的数据,key=序列值,value=下标。

        递归函数helper(int in_left, int in_right), 两个参数分别代表中序序列的左右边界值。

int preInx=0;int[] preorder;HashMapmap = new HashMap();public TreeNode buildTree(int[] preorder, int[] inorder) {  this.preorder = preorder;  for(int i =0;i    map.put(inorder[i],i);  }  return helper(0 , preorder.length-1);}private TreeNode helper(int in_left,int in_right){    if(in_left > in_right){        return null;    }    int root_val = preorder[preInx];    TreeNode root = new TreeNode(root_val);    int index = map.get(root_val);    preInx++;    root.left = helper(in_left,index -1);    root.right = helper(index +1 ,in_right);    return root;}

不积跬步,无以至千里。

文章有帮助的话,在看,转发吧。

谢谢支持哟 (*^__^*)

END

74e69d64a9668f40060c6e0591665fce.gif?74e69d64a9668f40060c6e0591665fce.gif

621ef131a2b423d55875ced44708b0e2.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值