力扣--根据前序、中序和后序来重建二叉树

二叉树的前序、中序和后序遍历:

  • 前序:根节点、左子树、右子树
  • 中序:左子树、根节点、右子树
  • 后序:左子树、右子树、根节点

一、根据前序中序来重建二叉树(剑指offer07题

1、题目:输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

2、示例

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

3、解题思路

核心思路都是要找下一次递归左子树所需的两个变量和右子树所需的两个变量。

在前序遍历结果中,最左边的元素preorder[0]就是二叉树的根节点,而在中序遍历的结果中,找到preorder[0]元素对应的下标,那么preorder[0]左边所有的元素是属于preorder[0]为根的左子树,preorder[0]右边的元素是以preorder[0]为根的右子树,然后进行递归。

4、代码

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder)==0:return
        root=TreeNode(preorder[0])
        root_index=inorder.index(root.val)

        root.left=self.buildTree(preorder[1:root_index+1],inorder[:root_index])
        root.right=self.buildTree(preorder[root_index+1:],inorder[root_index+1:])
        return root

二、根据中序后序来重建二叉树(力扣106题

只需要把前序和中序重建二叉树中的preorder[0]改为preorder[-1],因为后序遍历中根节点为最后一位,其他相同。

代码:

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if len(postorder)==0:return
        root=TreeNode(postorder[-1])
        root_index=inorder.index(root.val)

        left_inorder=inorder[:root_index]
        right_inorder=inorder[root_index+1:]

        len_left=len(left_inorder)

        left_postorder=postorder[:len_left]
        right_postorder=postorder[len_left:-1]

        root.left=self.buildTree(left_inorder,left_postorder)
        root.right=self.buildTree(right_inorder,right_postorder)

        return root

三、根据前序后序来重建二叉树(力扣889题

获取左子树中一共有多少个节点,同时也就知道了右子树总的节点数。前序遍历的第二个元素为左子树的根节点,在后序遍历中找到这个节点,并获取其下标,则该下标加1就是左子树总元素的个数。

代码:

class Solution(object):
    def constructFromPrePost(self, pre, post):
        if not pre:
            return None
        root = TreeNode(pre[0])
        if len(pre) == 1:
            return root

        left_num = post.index(pre[1]) + 1

        left_pre, right_pre = pre[1:left_num+1], pre[left_num+1:]
        left_post, right_post = post[:left_num], post[left_num:-1]

        root.left = self.constructFromPrePost(left_pre, left_post)
        root.right = self.constructFromPrePost(right_pre, right_post)
        return root

### LeetCode C++ 二叉树遍历实现 以下是基于给定引用内容以及专业知识所提供的解决方案。 #### 方法一:递归方法 递归是最直观的方式之一来完成二叉树的中遍历。按照定义,先访问左子树,接着访问根节点,最后访问右子树[^1]。 ```cpp #include <vector> using namespace std; // 定义二叉树节点结构 class TreeNode { public: int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; void inorderTraversalHelper(TreeNode* root, vector<int>& result) { if (root == nullptr) return; // 如果当节点为空,则返回 inorderTraversalHelper(root->left, result); // 访问左子树 result.push_back(root->val); // 访问根节点 inorderTraversalHelper(root->right, result); // 访问右子树 } vector<int> inorderTraversal(TreeNode* root) { vector<int> result; inorderTraversalHelper(root, result); return result; } ``` 上述代码通过辅助函数 `inorderTraversalHelper` 来递归地处理每一个节点及其子树[^2]。 --- #### 方法二:迭代方法(栈) 如果希望避免显式的递归调用,可以使用栈模拟递归过程。这种方法同样能够有效地实现中遍历[^5]。 ```cpp #include <stack> vector<int> inorderTraversalIterative(TreeNode* root) { vector<int> result; stack<TreeNode*> s; TreeNode* current = root; while (current != nullptr || !s.empty()) { // 不断向左走并将沿途节点压入栈中 while (current != nullptr) { s.push(current); current = current->left; } // 当无左子树可访问时,弹出栈顶并访问它 current = s.top(); s.pop(); result.push_back(current->val); // 转而访问右子树 current = current->right; } return result; } ``` 此方法利用栈保存尚未完全访问过的节点,在每次循环中优先探索左侧路径直到尽头后再回溯访问父节点右侧分支[^4]。 --- #### 复杂度分析 - **时间复杂度**: O(n),其中 n 是二叉树中的节点总数。无论是递归还是迭代方式都需要访问每个节点一次。 - **空间复杂度**: - 对于递归版本来说,其额外开销取决于递归深度,最坏情况下为 O(h),h 表示树的高度; - 迭代版则需借助显式的数据结构——栈存储部分未处理完毕的节点信息,因此平均情况下的空间消耗也为 O(h)[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值