Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
思路1:遞歸實作。
C++實作:
/**
* 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> inorderTraversal(TreeNode* root) {
ivec.clear();
inorder(root);
return ivec;
}
private:
vector<int> ivec;
void inorder(TreeNode* root){
if(root == NULL)
return;
inorder(root->left);
ivec.push_back(root->val);
inorder(root->right);
}
};
思路2:非遞歸實作。需要用一個輔助棧。
C++代碼實作:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ivec;
stack<TreeNode*> st;
if(root == NULL)
return ivec;
TreeNode *p = root;
while(p || !st.empty()){
if(p){
st.push(p);
p = p ->left;
}
else{
if(!st.empty()){
p = st.top();
st.pop();
ivec.push_back(p->val);
p = p->right;
}
}
}
return ivec;
}
};