题目描述
题目分析
可分别使用递归和栈实现
参考文章: 二叉树的中序遍历
递归实现
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res){
if(!root) return ;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root){
vector<int> res;
inorder(root, res);
return res;
}
};
时间复杂度为O(n),空间复杂度为O(n)
栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root){
vector<int> res;
stack<TreeNode*> stk;
while(root != NULL || !stk.empty()){
while(root != NULL){
stk.push(root);
root = root->lefet;
}
root = stk.top(); stk.pop();
res.push_back(root-val);
root = root->right;
}
return res;
}
};
时间复杂度O(n),空间复杂度O(n)