code:
/**
* 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 {
private:
void traversal(vector<int>&result,TreeNode*root)
{
if(root==NULL)return;
traversal(result,root->left);
result.push_back(root->val);
traversal(result,root->right);
return;
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
traversal(result,root);
return result;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
stack<TreeNode*>st;
TreeNode*cur=root;
while(cur||!st.empty())
{
if(cur)
{
st.push(cur);
cur=cur->left;
}
else
{
cur=st.top();
st.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
};