leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java

Posted xiaoba1203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java相关的知识,希望对你有一定的参考价值。

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

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

 

和上一道题基本一样

 

根据中序和后序遍历确定一个棵树。

 

/**
 * 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) {
      

        int len = inorder.length;
        if( len == 0)
            return null;

        return helper(inorder,0,len-1,postorder,len-1);

    }

    public TreeNode helper(int[] inorder,int start,int end, int[] postorder, int pos ){

        if( pos < 0 || start > end)
            return null;
        TreeNode node = new TreeNode(postorder[pos]);

        int size = 0;
        for( int i = end;i >= start && inorder[i] != postorder[pos];i--,size++)
            ;

        node.left = helper(inorder,start,end-size-1,postorder,pos-size-1);

        node.right = helper(inorder,end-size+1,end,postorder,pos-1);

        return node;

    }
}

 


以上是关于leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal

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

leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java

LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal

LeetCode-面试算法经典-Java实现106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)(示例(代码片

[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树