题目描述:左根右的遍历方式
方法1:递归
class Solution {
public:
void inorder(TreeNode* root,vector<int>value){
if(!root) return;
inorder(root->left,value);
value.push_back(root->val);
inorder(root->right,value);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> value;
inorder(root,value);
return value;
}
};
出现错误,vector<int> value被传递的是拷贝而不是引用,导致递归中的修改无法反映到原来的vector<int> value中。需要将vector<int> value作为引用传递,即
void inorder(TreeNode* root,vector<int>&value)
方法二:非递归方式,与前序不一样,
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>vals;
if(!root) return vals;
stack<TreeNode*>stk;
TreeNode* temp = root;
while(temp || !stk.empty()){
while(temp){
stk.push(temp);
temp = temp->left;
}//左孩子一直入栈
temp = stk.top();
stk.pop();
vals.push_back(temp->val);
temp = temp->right;
}
return vals;
}
};