LeetCode – Refresh – Construct Binary Tree from Inorder and Postorder Traversal

本文详细介绍了如何通过中序和后序遍历序列重建二叉树,包括关键步骤和实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

For this problem just need to know the structure of two traversal.

1. It is hard to find the root node in the inorder traversal but it is easy in postorder. The last one in post order is the root. 

2. At same time, you can not figure out what is the boundary for left branch and right branch in post order. But you can do it in inorder.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) {
13         if (ist > ied) return NULL;
14         int current = -1, len = 0;
15         for (int i = ist; i <= ied; i++) {
16             if (pv[ped] == iv[i]) {
17                 current = i;
18                 break;
19             }
20         }
21         len = current - ist;
22         TreeNode *root = new TreeNode(pv[ped]);
23         root->left = getTree(iv, pv, ist, current-1, pst, pst+len-1);
24         root->right = getTree(iv, pv, current+1, ied, pst+len, ped-1);
25     }
26     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
27         if (inorder.size() == 0 || inorder.size() != postorder.size()) return NULL;
28         return getTree(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
29     }
30 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4349275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值