Leetcode105 & 106. Construct Binary Tree from Preorder and Inorder Traversal

本文详细介绍了如何使用前序遍历和中序遍历,以及前序遍历和后序遍历来构建二叉树的方法。通过递归算法,解析了不同遍历方式下构建二叉树的具体实现过程。

根据前序遍历和中序遍历构建一个二叉树
我真是一个可恨的菜逼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public TreeNode build(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right){
        TreeNode root = new TreeNode(preorder[pre_left]);
        
        if(pre_left == pre_right){
            return root;
        }
        
        int i;
        for(i= 0; i <= in_right; i++){
            if(inorder[i] == preorder[pre_left])break;
        }
        
        if(i - 1 >= in_left)
            root.left = build(preorder,inorder, pre_left + 1, pre_right + (i - in_left), in_left, i-1);
        if(i + 1 <= in_right)
            root.right = build(preorder, inorder, pre_left + (i - in_left) + 1, pre_right, i+1, in_right);
        return root;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0){
            return null;
        }
        return build(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
    }
}

然后是根据前序遍历和后序遍历构建一个二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public TreeNode build(int[] inorder, int[] postorder, int in_left, int in_right, int post_left, int post_right){
        TreeNode root = new TreeNode(postorder[post_right]);
        
        if(in_left == in_right)return root;
        
        int i;
        for(i = in_left; i <= in_right; i++){
            if(root.val == inorder[i])break;
        }
        
        
        if(i-1 >= in_left)
            root.left = build(inorder,postorder,in_left, i-1,post_left, post_left + (i-1 - in_left));
        if(i+1 <= in_right)
            root.right = build(inorder,postorder, i+1,in_right,post_right - in_right + i,post_right-1);
        return root;
    }
    
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0 || postorder.length == 0)return null;
        return build(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
    }
}
下面是该段代码的 **Visual Studio 可运行完整版本**,包含: - `TreeNode` 节点定义 - `buildTree` 函数的完整实现(从前序和中序遍历构造二叉树) - 主函数中测试用例 - 打印构建后的二叉树(前序遍历验证) --- ## ✅ Visual Studio 完整运行代码 ```cpp #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;ranges&gt; using namespace std; // 二叉树节点定义 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; class Solution { public: TreeNode* buildTree(vector&lt;int&gt;&amp; preorder, vector&lt;int&gt;&amp; inorder) { if (preorder.empty()) { return nullptr; } // 查找根节点在中序遍历中的位置 auto root_it = ranges::find(inorder, preorder[0]); int left_size = distance(inorder.begin(), root_it); // 左子树节点数量 // 划分左子树和右子树的前序和中序序列 vector&lt;int&gt; pre_left(preorder.begin() + 1, preorder.begin() + 1 + left_size); vector&lt;int&gt; pre_right(preorder.begin() + 1 + left_size, preorder.end()); vector&lt;int&gt; in_left(inorder.begin(), inorder.begin() + left_size); vector&lt;int&gt; in_right(inorder.begin() + 1 + left_size, inorder.end()); // 递归构建左右子树 TreeNode* left = buildTree(pre_left, in_left); TreeNode* right = buildTree(pre_right, in_right); return new TreeNode(preorder[0], left, right); } // 前序遍历打印二叉树 void preorderPrint(TreeNode* root) { if (root == nullptr) { cout &lt;&lt; &quot;null &quot;; return; } cout &lt;&lt; root-&gt;val &lt;&lt; &quot; &quot;; preorderPrint(root-&gt;left); preorderPrint(root-&gt;right); } // 析构函数(手动释放内存) void deleteTree(TreeNode* root) { if (root == nullptr) return; deleteTree(root-&gt;left); deleteTree(root-&gt;right); delete root; } }; int main() { Solution sol; // 示例输入 vector&lt;int&gt; preorder = {3, 9, 20, 15, 7}; vector&lt;int&gt; inorder = {9, 3, 15, 20, 7}; // 构建二叉树 TreeNode* root = sol.buildTree(preorder, inorder); // 打印前序遍历结果以验证是否正确 cout &lt;&lt; &quot;构建的二叉树前序遍历结果: &quot;; sol.preorderPrint(root); cout &lt;&lt; endl; // 释放内存 sol.deleteTree(root); return 0; } ``` --- ## 📌 编译与运行说明(适用于 Visual Studio) 1. 打开 Visual Studio 2. 创建一个 **C++ 控制台应用程序(Console Application)** 3. 删除默认生成的代码内容 4. 将上面的代码粘贴到 `.cpp` 文件中(如 `main.cpp`) 5. 确保你的编译器支持 **C++20**,因为使用了 `&lt;ranges&gt;` 和范围查找 - VS 2022 及以上版本支持 C++20 6. 按 `Ctrl + F5` 或点击 **&ldquo;本地 Windows 调试器&rdquo;** 运行程序 --- ## 🧾 输出结果示例 ``` 构建的二叉树前序遍历结果: 3 9 null null 20 15 null null 7 null null ``` 说明构建成功,结构如下: ``` 3 / \ 9 20 / \ 15 7 ``` --- ## 🧠 代码解释 - `preorder[0]` 是当前子树的根节点。 - 在 `inorder` 中找到该根节点,左边就是左子树,右边就是右子树。 - 根据左子树大小,划分 `preorder` 中的左右子树。 - 递归构造左右子树。 - 最后返回构造好的当前子树根节点。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值