题目链接:
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
难度:中等
94. 二叉树的中序遍历
给定一个二叉树,返回它的中序遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Un lote simple sin considerar avanzado. . . . Solo recurre directamente
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(root==nullptr){
return ans;
}
dfs(root,ans);
return ans;
}
void dfs(TreeNode* root,vector<int> &ans){
if(root->left!=nullptr){
dfs(root->left,ans);
}
ans.push_back(root->val);
if(root->right!=nullptr){
dfs(root->right,ans);
}
}
};
Entonces, el código es el siguiente cuando se usa la iteración, y se produce un error cuando la iteración del recorrido de orden medio no era muy competente en la escritura. . . Un lugar no comprende
root = root-> right; Antes de eso, se han enumerado el nodo actual y el subárbol izquierdo, y luego se debe enumerar el subárbol derecho del nodo actual. Si el subárbol derecho del nodo actual (o nodo derecho) es Vaciar y luego tomar sta.top () en el siguiente ciclo
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(root==nullptr){
return ans;
}
stack<TreeNode*> sta;
while(!sta.empty()||root!=nullptr){
while(root!=nullptr){
sta.push(root);
root=root->left;
}
root=sta.top();
sta.pop();
ans.push_back(root->val);
root=root->right;
}
return ans;
}
};