前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >106. 从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树

作者头像
张伦聪zhangluncong
发布2022-10-26 18:02:18
1130
发布2022-10-26 18:02:18
举报

根据一棵树的中序遍历与后序遍历构造二叉树。

注意: 你可以假设树中没有重复的元素。

例如,给出

代码语言:javascript
复制
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

解:跟105题差不多

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public TreeNode buildTree2(int[] inorder, int[] postorder) {
        return build2(inorder, postorder, postorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode build2(int[] inorder, int[] postorder, int postEnd, int inSt, int inEnd) {
        //递归临界点
        if (postEnd < 0 || inSt > inEnd) {
            return null;
        }
        //后序遍历尾节点为根节点
        TreeNode rootNode = new TreeNode(postorder[postEnd]);
        //根节点在中序遍历的索引
        int rootIndex = 0;
        for (int i = inSt; i <= inEnd; i++) {
            if (inorder[i] == rootNode.val) {
                rootIndex = i;
                break;
            }
        }
        int rightLength = inEnd - rootIndex;
        int postEndLeft = postEnd - rightLength - 1;
        int postEndRight = postEnd - 1;
        rootNode.left = build2(inorder, postorder, postEndLeft, inSt, rootIndex - 1);
        rootNode.right = build2(inorder, postorder, postEndRight, rootIndex + 1, inEnd);
        return rootNode;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-07-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档