@@ -70,7 +70,7 @@
|
||||
|
||||
那么本题要构造二叉树,依然用递归函数的返回值来构造中节点的左右孩子。
|
||||
|
||||
再来看参数,首先是传入数组,然后就是左下表left和右下表right,我们在[二叉树:构造二叉树登场!](https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html)中提过,在构造二叉树的时候尽量不要重新定义左右区间数组,而是用下表来操作原数组。
|
||||
再来看参数,首先是传入数组,然后就是左下标left和右下标right,我们在[二叉树:构造二叉树登场!](https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html)中提过,在构造二叉树的时候尽量不要重新定义左右区间数组,而是用下标来操作原数组。
|
||||
|
||||
所以代码如下:
|
||||
|
||||
@@ -144,7 +144,7 @@ public:
|
||||
|
||||
## 迭代法
|
||||
|
||||
迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下表,一个队列放右区间下表。
|
||||
迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下标,一个队列放右区间下标。
|
||||
|
||||
模拟的就是不断分割的过程,C++代码如下:(我已经详细注释)
|
||||
|
||||
@@ -156,11 +156,11 @@ public:
|
||||
|
||||
TreeNode* root = new TreeNode(0); // 初始根节点
|
||||
queue<TreeNode*> nodeQue; // 放遍历的节点
|
||||
queue<int> leftQue; // 保存左区间下表
|
||||
queue<int> rightQue; // 保存右区间下表
|
||||
queue<int> leftQue; // 保存左区间下标
|
||||
queue<int> rightQue; // 保存右区间下标
|
||||
nodeQue.push(root); // 根节点入队列
|
||||
leftQue.push(0); // 0为左区间下表初始位置
|
||||
rightQue.push(nums.size() - 1); // nums.size() - 1为右区间下表初始位置
|
||||
leftQue.push(0); // 0为左区间下标初始位置
|
||||
rightQue.push(nums.size() - 1); // nums.size() - 1为右区间下标初始位置
|
||||
|
||||
while (!nodeQue.empty()) {
|
||||
TreeNode* curNode = nodeQue.front();
|
||||
@@ -267,9 +267,9 @@ class Solution {
|
||||
|
||||
// 根节点入队列
|
||||
nodeQueue.offer(root);
|
||||
// 0为左区间下表初始位置
|
||||
// 0为左区间下标初始位置
|
||||
leftQueue.offer(0);
|
||||
// nums.size() - 1为右区间下表初始位置
|
||||
// nums.size() - 1为右区间下标初始位置
|
||||
rightQueue.offer(nums.length - 1);
|
||||
|
||||
while (!nodeQueue.isEmpty()) {
|
||||
|
||||
Reference in New Issue
Block a user