您的位置:首页 > 其它

LeetCode-106. Construct Binary Tree from Inorder and Postorder Traversal

2017-10-08 19:42 453 查看

题目描述

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

解题思路

根据二叉树中序遍历(左中右)和后序遍历(左右中)的结果恢复二叉树,和LeetCode-105相同的思路,也是用递归和遍历两种方式求解。递归很好理解。遍历的求解方式,可以通过画图的方式确定各种关系。

代码

递归

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0)
return null;
return buildCore(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
private TreeNode buildCore(int[] inorder,int startin,int endin,int[] postorder,int startpost,int endpost){
if(startin > endin || startpost > endpost)
return null;
TreeNode root = new TreeNode(postorder[endpost]);
int position = -1;
for(int i=startin;i<=endin;i++){
if(postorder[endpost] == inorder[i]){
position = i;
break;
}
}
root.left = buildCore(inorder,startin,position-1,postorder,startpost,position-startin+startpost-1);
root.right = buildCore(inorder,position+1,endin,postorder,position-startin+startpost,endpost-1);
return root;
}
}


遍历的方式

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0)
return null;
//return buildCore(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode root = new TreeNode(postorder[postorder.length-1]);
stack.push(root);
int index = inorder.length-1;
for(int i=postorder.length-2;i>=0;i--){
TreeNode cur = stack.peek();
if(cur.val != inorder[index]){
cur.right = new TreeNode(postorder[i]);
stack.push(cur.right);
}else{
while(stack.size() != 0 && stack.peek().val == inorder[index]){
cur = stack.pop();index--;
}
if(index >= 0){
cur.left = new TreeNode(postorder[i]);
stack.push(cur.left);
}
}
}
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐