94. Binary Tree Inorder Traversal
porblem description
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]algorithm thought
code
algorigthm thought
Last updated
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]Last updated
/**
* 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> res;
void inorder(TreeNode* root)
{
if(root==NULL)
return;
inorder(root->left);
res.push_back(root->val);
inorder(root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
inorder(root);
return res;
}
};
//迭代写法
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
while(root||!st.empty()){
while(root){
st.push(root);
root=root->left;
}
root=st.top();
st.pop();
res.push_back(root->val);
root=root->right;
}
return res;
}
};
//morris
lass Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode* prev=NULL;
while(root){
if(root->left==NULL){
res.push_back(root->val);
root=root->right;
}else{
prev=root->left;
while(prev->right&&prev->right!=root){
prev=prev->right;
}
if(prev->right==NULL){
prev->right=root;
root=root->left;
}else{
root=prev->right;
prev->right=NULL;
res.push_back(root->val);
root=root->right;
}
}
}
return res;
}
};