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 Solution1 {
public:
void inorder(TreeNode *root,vector<int>& vec) {
if(root==nullptr)return ;
inorder(root->left,vec);
vec.push_back(root->val);
inorder(root->right,vec);
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> vec;
if(root==nullptr)return vec;
inorder(root,vec);
return vec;
}
};
//迭代 显示维护一个栈
class Solution2 {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> vec;
if(root==nullptr)return vec;
stack<TreeNode*> stk;
while(root!=nullptr || !stk.empty()) {
while(root) {//先将左子树入栈
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
vec.emplace_back(root->val);
root = root->right;//在遍历右子树
}
return vec;
}
};
LeetCode 94. 二叉树的中序遍历 题解 C/C++
于 2021-04-17 23:26:21 首次发布