LeetCode //C - 105. Construct Binary Tree from Preorder and Inorder Traversal

这篇具有很好参考价值的文章主要介绍了LeetCode //C - 105. Construct Binary Tree from Preorder and Inorder Traversal。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

105. Construct Binary Tree from Preorder and Inorder Traversal

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
 

Example 1:

LeetCode //C - 105. Construct Binary Tree from Preorder and Inorder Traversal,LeetCode,leetcode,c语言,算法

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: preorder = [-1], inorder = [-1]
Output: [-1]

Constraints:
  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values.
  • Each value of inorder also appears in preorder.
  • preorder is guaranteed to be the preorder traversal of the tree.
  • inorder is guaranteed to be the inorder traversal of the tree.

From: LeetCode
Link: 105. Construct Binary Tree from Preorder and Inorder Traversal


Solution:

Ideas:

The idea behind the solution is based on the following key observations regarding the properties of the preorder and inorder traversals of a binary tree:

  1. Preorder Traversal (Root, Left, Right):
  • The first element in the preorder traversal gives the root of the tree/subtree.
  • Subsequent elements can be divided into two groups based on this root: the left subtree nodes and the right subtree nodes.
  1. Inorder Traversal (Left, Root, Right):
  • Given a root, you can determine the number of nodes in the left and right subtrees by finding the root’s position in the inorder traversal.
  • All elements to the left of the root in the inorder traversal belong to the left subtree. Similarly, all elements to the right of the root belong to the right subtree.

Using these properties, the algorithm constructs the binary tree in the following manner:

  1. Base Case: If the provided subsections of the preorder or inorder lists are empty (i.e., start index is greater than the end index), return NULL. This means there’s no tree to be constructed for that particular subsection.

  2. Recursive Steps:文章来源地址https://www.toymoban.com/news/detail-701299.html

  • Take the first element from the preorder list as the current root of the tree/subtree.
  • Find the position of this root in the inorder list. This will effectively split the inorder list into two parts: nodes belonging to the left subtree and nodes belonging to the right subtree.
  • Calculate the lengths of these left and right subtrees.
  • Use these lengths to determine the sections of the preorder list that correspond to the left and right subtrees.
  • Make recursive calls to construct the left and right subtrees using the subsections of the preorder and inorder lists corresponding to the left and right subtrees, respectively.
  • Connect the constructed left and right subtrees to the current root.
  1. Return the constructed tree.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int indexOf(int* arr, int start, int end, int value) {
    for (int i = start; i <= end; i++) {
        if (arr[i] == value) {
            return i;
        }
    }
    return -1;
}

struct TreeNode* helper(int* preorder, int preorderStart, int preorderEnd, 
                        int* inorder, int inorderStart, int inorderEnd) {
    if (preorderStart > preorderEnd || inorderStart > inorderEnd) {
        return NULL;
    }
    
    // Create the root node with the first value of the preorder list
    struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
    root->val = preorder[preorderStart];
    
    // Get the position of root in inorder
    int rootIndex = indexOf(inorder, inorderStart, inorderEnd, root->val);
    
    // Calculate the length of the left and right subtrees
    int leftTreeLength = rootIndex - inorderStart;
    int rightTreeLength = inorderEnd - rootIndex;
    
    // Construct left and right subtrees
    root->left = helper(preorder, preorderStart + 1, preorderStart + leftTreeLength, 
                        inorder, inorderStart, rootIndex - 1);
    
    root->right = helper(preorder, preorderStart + leftTreeLength + 1, preorderEnd, 
                         inorder, rootIndex + 1, inorderEnd);
    
    return root;
}

struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    return helper(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1);
}

到了这里,关于LeetCode //C - 105. Construct Binary Tree from Preorder and Inorder Traversal的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Leetcode 1367. Linked List in Binary Tree (二叉树好题)

    Linked List in Binary Tree Medium Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. Exampl

    2024年01月25日
    浏览(47)
  • LeetCode //C - 114. Flatten Binary Tree to Linked List

    Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” should be in the same order as a pre-order traversal of the binary tree.   Example 1: Input: ro

    2024年02月09日
    浏览(36)
  • LeetCode //C - 1161. Maximum Level Sum of a Binary Tree

    Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal.   Example 1: Input: root = [1,7,0,7,-8,null,null] Output: 2 **Explanation: ** Level 1 sum = 1. Level 2 sum = 7 + 0 = 7. Level 3 sum = 7 + -8 = -1. So we return

    2024年01月23日
    浏览(49)
  • LintCode 650 · Find Leaves of Binary Tree (binary tree 后序遍历非常好的题目!)

    650 · Find Leaves of Binary Tree Algorithms Medium Description Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Example Example1 Input: {1,2,3,4,5} Output: [[4, 5, 3], [2], [1]]. Explanation: / 2 3 / 4 5 Example2 Input: {1,2,3,4} Output: [[4, 3], [2], [1]]. Explanation:

    2024年02月20日
    浏览(37)
  • 二叉树(binary tree)

    二叉树(Binary Tree)是一种常见的树状数据结构,它由一组节点组成,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树具有以下特点: 每个节点最多有两个子节点,分别称为左子节点和右子节点。 左子树和右子树也是二叉树,它们的结构与父节点类似。

    2024年02月09日
    浏览(42)
  • 平衡二叉树(Balanced Binary Tree)

    平衡二叉树是一种特殊的二叉搜索树,它具有以下特点: 每个节点的左子树和右子树的高度差不超过1。 所有的子树也都是平衡二叉树。 通过保持平衡性,平衡二叉树可以在最坏情况下仍然具有较好的性能,保证查找、插入和删除操作的时间复杂度为O(log n)。 平衡二叉树的常

    2024年02月09日
    浏览(36)
  • 数据结构与算法 | 二叉树(Binary Tree)

    二叉树(Binary Tree)是一种树形数据结构,由节点构成,每个节点最多有两个子节点:一个左子节点和一个右子节点。 \\\"二叉树\\\"(Binary Tree)这个名称的由来是因为二叉树的每个节点最多有两个子节点,一个左子节点和一个右子节点。其中,“二叉”指的是两个,因此“二叉树

    2024年02月08日
    浏览(40)
  • 二叉搜索树(Binary_Search_Tree)

    二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树: 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值。 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值。 它的左右子树也分别为二叉搜索树。 如: a、从根开始

    2024年04月28日
    浏览(36)
  • 【C++】二叉搜索树Binary Search Tree

    二叉搜索树又被称为二叉排序树,顾名思义,当我们使用中序遍历时,会得到一个有序的序列。二叉搜索树有如下的性质: 1.若它的左子树不为空,则左子树上每个节点的值都小于根节点的值。 2.若它的右子树不为空,则右子树上每个节点的值都大于根节点的值。 3.左右子树

    2024年02月07日
    浏览(44)
  • 二叉查找树(binary search tree)(难度7)

    C++数据结构与算法实现(目录) 答案在此:二叉查找树(binary search tree)(答案) 写在前面 部分内容参《算法导论》 基本接口实现 1 删除 删除值为value的第一个节点 删除叶子节点1 删除叶子节点1 (3)删除叶子节点1 删除有两个孩子的节点z 分成下面几个步骤进行: 1 找到

    2024年02月10日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包