题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

alt

alt

解题思路

  1. 先序遍历第一个元素一定是当前的根节点
  2. 中序遍历里,根节点的左侧一定是在根节点左边,右侧的一定是在右边

基于以上两点,先将pre中第一个元素入根节点,然后遍历找到根节点在vin中的位置site。

root->lift 即遍历pre 1~site 和 vin 0-site 的内容

root->right 即遍历pre (site + 1) ~ 7 和 vin (site + 1) ~ 7 的内容

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pre int整型一维数组 
 * @param preLen int pre数组长度
 * @param vin int整型一维数组 
 * @param vinLen int vin数组长度
 * @return TreeNode类
 */
struct TreeNode* reConstructBinaryTree(int* pre, int preLen, int* vin, int vinLen ) {
    // write code here
    struct TreeNode* pRoot = 0;
    int iSite = 0;
    
    if ((NULL == pre) || (0 == preLen))
        return NULL;
    
    pRoot = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    memset(pRoot, 0, sizeof(struct TreeNode));
    pRoot->val = pre[0];
    while (pre[0] != vin[iSite])
    {
        iSite++;
    }
    pRoot->left = reConstructBinaryTree(pre + 1, iSite, vin, iSite);
    pRoot->right = reConstructBinaryTree(pre + iSite + 1, preLen - iSite - 1, vin + iSite + 1, vinLen - iSite - 1);
    
    return pRoot;
}
全部评论
讲解的很细,建议不知所措的人不要直接看代码先看一遍流程
点赞 回复 分享
发布于 2022-04-11 17:10

相关推荐

评论
10
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务