美文网首页
106. Construct Binary Tree from

106. Construct Binary Tree from

作者: liuhaohaohao | 来源:发表于2018-06-02 20:00 被阅读0次

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

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

    For example, given

    inorder = [9,3,15,20,7]
    postorder = [9,15,7,20,3]
    

    Return the following binary tree:

        3
       / \
      9  20
        /  \
       15   7
    

    Solution

    /**
     * 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) {
            return helper(postorder.length - 1, 0, inorder.length - 1, inorder, postorder);
        }
        public TreeNode helper(int postEnd, int inStart, int inEnd, int[] inorder, int[] postorder){
            if (0 > postEnd || inStart > inEnd){
                return null;
            }
            
            TreeNode root = new TreeNode(postorder[postEnd]);
            int inIndex = 0;
            for (int i = inStart; i <= inEnd; i++){
                if (root.val == inorder[i]){
                    inIndex = i;
                }
            }
            
            root.right = helper(postEnd - 1, inIndex + 1, inEnd, inorder, postorder);
            root.left = helper(postEnd - 1 - (inEnd - inIndex), inStart, inIndex - 1, inorder, postorder);
            return root;
            
        }
    }
    

    相关文章

      网友评论

          本文标题:106. Construct Binary Tree from

          本文链接:https://www.haomeiwen.com/subject/zezrsftx.html