个人记录-LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:网络调试助手的作用 编辑:程序博客网 时间:2024/05/18 17:41

问题:
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类似,
不同的是给的数组时中序遍历和后序遍历得到的结果。

        5      /   \     2     7    / \   / \   1   3  6  9

对于上图中的树而言,
其中序遍历的结果为: 1 2 3 5 6 7 9
其后序遍历的结果为: 1 3 2 6 9 7 5

容易看出,我们应该从后序遍历的结尾找到根节点,
然后根据根节点 及中序遍历的结果,
将数组拆分为左右子树,然后继续递归。

这里的解法与LeetCode 105类似,
不过这次没有进行数组的copy操作,
而是修改每次的取值范围。


代码示例:

/** * 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) {            return null;        }        if (inorder.length != postorder.length || inorder.length == 0) {            return null;        }        //初始为整个数组长度        return innerHelper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);    }    private TreeNode innerHelper(int[] inorder, int beginIn, int endIn,            int[] postorder, int beginPo, int endPo) {        //从后序遍历的末尾拿到根节点        int rootVal = postorder[endPo];        TreeNode root = new TreeNode(rootVal);        //遍历中序数组,得到左子树的长度        //在本次的取值范围中遍历即可        int count = 0;        for (int i = beginIn; i <= endIn; ++i) {            if (inorder[i] == rootVal) {                break;            }            ++count;        }        //构造左子树        if (count > 0) {            //结合上面的例子,应该比较好计算左子树的中序、后序index范围            root.left = innerHelper(inorder, beginIn, beginIn + count - 1,                    postorder, beginPo, beginPo + count - 1);        }        //构造右子树        int rest = endIn - beginIn - count;        if (rest > 0) {            //结合上面的例子,计算右子树的中序、后序index范围            root.right = innerHelper(inorder, beginIn + count + 1, endIn,                    postorder, beginPo + count, endPo - 1);        }        return root;    }}
0 0
原创粉丝点击