106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:云舒网络 拖欠工资 编辑:程序博客网 时间:2024/05/23 12:04

Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

解题思路:利用后序和中序结果重建二叉树,思路和105那道题一样,既可以递归也可以非递归。
一刷ac
递归方法。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {        if(inorder == null || postorder == null | inorder.length == 0 || postorder.length ==0) return null;        return builder(inorder, 0, inorder.length-1, postorder, postorder.length-1);    }    public static TreeNode builder(int[] inorder, int in_start, int in_end, int[] postorder, int post_end){        if(in_start > in_end || post_end < 0) return null;        TreeNode node = new TreeNode(postorder[post_end]);        for(int i = in_start; i <= in_end; i++){            if(postorder[post_end] == inorder[i]){                node.left = builder(inorder, in_start, i-1, postorder, post_end+i-in_end-1);                node.right = builder(inorder, i+1, in_end, postorder, post_end-1);            }        }        return node;    }}

非递归

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {        if(inorder == null || postorder == null | inorder.length == 0 || postorder.length ==0) return null;        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 node = stack.peek();            if(node.val == inorder[index]){                while(!stack.isEmpty() && stack.peek().val == inorder[index]){                    index--;                    node = stack.pop();                }                TreeNode tmp = new TreeNode(postorder[i]);                node.left = tmp;                stack.push(tmp);            }else{                TreeNode tmp = new TreeNode(postorder[i]);                node.right = tmp;                stack.push(tmp);            }        }        return root;    }}
0 0