【数据结构】二叉树专题
94. 二叉树的中序遍历
递归写法
/**
* Definition for a binary tree node.
* struct TreeNode {
* 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) {}
* };
*/
class Solution {
public:
vector res;
void dfs(TreeNode* root)
{
if(!root) return;
dfs(root->left);
res.push_back(root->val);
dfs(root->right);
}
vector inorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
作者:Once.
链接:https://www.acwing.com/activity/content/code/content/3201627/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
非递归写法(利用栈,固定套路,要求背会)
中序遍历的非递归写法:
1.遍历一棵子树时,将这棵子树的左链全部加入到栈中(因为遍历顺序是左根右)
2.每次取出栈顶元素,遍历栈顶元素,然后删掉栈顶元素(出栈),删完之后看一下这个点是否有右子树,如果有右子树的话就把右子树的左链放到栈里。
/**
* Definition for a binary tree node.
* struct TreeNode {
* 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) {}
* };
*/
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
vector res; // 定义答案数组
stack stk; // 定义栈
while(root || stk.size()) // 当当前结点非空或栈非空时
{
while(root) // 当当前结点不空时
{
stk.push(root); // 将当前结点入栈
root = root->left; // 当前结点走到其左儿子的位置
}
root = stk.top(); // 将栈顶元素的值取出
stk.pop(); // 将栈顶元素弹出
res.push_back(root->val); // 遍历当前点
root = root->right; // 遍历完之后走到当前结点的右儿子
}
return res; // 返回答案数组
}
};
作者:Once.
链接:https://www.acwing.com/activity/content/code/content/3201627/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
173. 二叉搜索树迭代器
本质就是考察二叉树的中序遍历(非递归写法),同94
/**
* Definition for a binary tree node.
* struct TreeNode {
* 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) {}
* };
*/
class BSTIterator {
public:
stack stk;
BSTIterator(TreeNode* root) {
while(root)
{
stk.push(root);
root = root->left;
}
}
int next() {
auto root = stk.top();
stk.pop();
int val = root->val;
root = root->right;
while(root)
{
stk.push(root);
root = root->left;
}
return val;
}
bool hasNext() {
return stk.size();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/