LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal(Medium)

Description:
Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, …, pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

Analysis:
The key point of the problem is to figure out the intervals of indexes of left subtree and right subtree in pre  and post respectively. Here we use L to denote the number of nodes in the left subtree. Then we can get the following graph:
在这里插入图片描述

As the following graph show, traverse the post  until an element that is equal to pre[1]is found, this element represents the root node of the left subtree in post, then we can obtain the value of L. We can use a recursion to apply this strategy to construct the root node, left subtree and right subtree.


Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode constructFromPrePost(int[] pre, int[] post) {
        if(pre.length == 0) {
            return null;
        }else if(pre.length == 1) {
            return new TreeNode(pre[0]);
        }else{
            TreeNode root = new TreeNode(pre[0]);
            
            int N = pre.length;
            int L = 0;
            for(int i = 0; i < N; i++) {
                L += 1;
                if(post[i] == pre[1]) {
                    break;
                }
            }
            
            root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L+1), Arrays.copyOfRange(post, 0, L));
            root.right = constructFromPrePost(Arrays.copyOfRange(pre, L+1, N), Arrays.copyOfRange(post, L, N-1));
            
            return root;
        }
    }
}
<think>我们将把给定的Java代码转换为Python代码。原Java代码实现了二叉树的前序遍历(递归方式)。 前序遍历的顺序是:根节点 -> 左子树 -> 右子树。 在Python中,我们同样可以定义一个TreeNode类来表示二叉树的节点,然后实现递归的前序遍历。 注意:在Python中,我们通常使用列表(list)来存储遍历结果。 步骤: 1. 定义TreeNode类(如果题目中已经定义,则不需要重复定义,这里为了完整起见,我们给出定义)。 2. 实现一个Solution类,其中包含preorderTraversal方法,该方法接收一个根节点,返回一个整数列表。 3.preorderTraversal方法中,我们初始化一个空列表,然后调用递归辅助函数进行遍历。 4. 递归辅助函数preorder将节点和结果列表作为参数,按照前序遍历的顺序将节点值添加到列表中。 考虑到LeetCode的环境,我们假设TreeNode类已经定义好。因此,我们只需要写出Solution类的代码。 下面是转换后的Python代码:</think>### 二叉树前序遍历的 Python 实现 以下是 Java 代码的等效 Python 实现,使用递归方法完成二叉树的前序遍历: ```python from typing import List, Optional # 定义二叉树节点类 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: result = [] # 存储遍历结果的列表 self.preorder(root, result) # 调用递归方法 return result def preorder(self, node: Optional[TreeNode], result: List[int]) -> None: # 递归终止条件:遇到空节点 if node is None: return # 前序遍历步骤: # 1. 访问当前节点(添加到结果列表) result.append(node.val) # 2. 递归遍历左子树 self.preorder(node.left, result) # 3. 递归遍历右子树 self.preorder(node.right, result) ``` ### 代码解释: 1. **TreeNode 类**: - Python 使用类定义二叉树节点 - `__init__` 构造函数初始化节点值、左子节点和右子节点 - 使用 `Optional` 类型表示节点可以为 None 2. **Solution 类**: - `preorderTraversal` 方法: - 初始化空列表 `result` 存储结果 - 调用递归辅助方法 `preorder` - 返回最终结果列表 - `preorder` 递归辅助方法: - **基线条件**:当节点为 None 时直接返回 - **递归过程**: 1. 访问当前节点(添加到结果列表) 2. 递归遍历左子树 3. 递归遍历右子树 3. **前序遍历顺序**: - 根节点 → 左子树 → 右子树 - 示例:对于二叉树 `[1,null,2,3]`: ``` 1 \ 2 / 3 ``` 输出结果为 `[1,2,3]` ### 使用示例: ```python # 构建示例二叉树: # 1 # \ # 2 # / # 3 # 创建节点 n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) # 构建树结构 n1.right = n2 n2.left = n3 # 执行遍历 solution = Solution() print(solution.preorderTraversal(n1)) # 输出: [1, 2, 3] ``` ### 复杂度分析: - **时间复杂度**:O(n),每个节点恰好访问一次 - **空间复杂度**:O(h),其中 h 是二叉树的高度(递归调用栈空间) - 最坏情况(树退化为链表):O(n) - 平衡二叉树情况:O(log n)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值