[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:人工智能出版文献 编辑:程序博客网 时间:2024/05/29 04:55

题目描述

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

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

已知一棵二叉树的中序和后续遍历,构造出一棵二叉树。假设二叉树的节点无重复。

解题思路

乍一看题,好似无从解决,但画一个二叉树,并写出它的中序遍历和后序遍历结果,即可发现规律。


上图中可以发现后序遍历的数组的末尾元素即为根节点,根据根节点数值可以确定中序遍历数组中根节点的位置pos,继而可以得到:
  1. 左子树的中序遍历数组长度为pos-1,元素为inorder[0]~inorder[pos-1];
  2. 左子树的后序遍历数组长度为pos-1,元素为postorder[0]~postorder[pos-1];
  3. 右子树的中序遍历数组长度为inorder.length-1-pos,元素为inorder[pos+1]~inorder[inorder.length-1];
  4. 右子树的中序遍历数组长度为inorder.length-1-pos,元素为postorder[pos]~postorder[postorder.length-2]。
通过规律,我们很容易得到本题的递归解法。
至于本题的非递归解法还在研究中,容以后补上;

代码

public TreeNode buildTree(int[] inorder, int[] postorder) {        TreeNode root;        int pos = 0;                if(inorder==null || postorder==null){        return null;        }        if(inorder.length==0|| postorder.length==0){        return null;        }                root = new TreeNode(postorder[postorder.length - 1]);        for(int i = 0;i < inorder.length;i++){        if(inorder[i]==postorder[postorder.length - 1]){        pos = i;        break;        }        }                int[] inorderLeftChild = Arrays.copyOfRange(inorder, 0, pos);        int[] postorderLeftChild = Arrays.copyOfRange(postorder, 0, pos);                int[] inorderRightChild = Arrays.copyOfRange(inorder, pos+1, inorder.length);        int[] postorderRightChild = Arrays.copyOfRange(postorder, pos, postorder.length-1);                TreeNode leftChild = buildTree(inorderLeftChild,postorderLeftChild);        TreeNode rightChild = buildTree(inorderRightChild,postorderRightChild);                root.left = leftChild;        root.right = rightChild;        return root;}


0 0
原创粉丝点击