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]
.
Note: Recursive solution is trivial, could you do it iteratively?
从这道题可以总结一下二叉树遍历的方法。方法一:递归,很直观。
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ret;
traversal(ret,root);
return ret;
}
void traversal(vector<int>& ret,TreeNode* root)
{
if(root == NULL) return;
traversal(ret,root->left);
ret.push_back(root->val);
traversal(ret,root->right);
}
};
20 milli secs.
方法二:迭代,需要用栈存储路径。
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ret;
stack<TreeNode*> stack;
while(root != NULL || !stack.empty())
{
if(root == NULL){
root = stack.top();
stack.pop();
ret.push_back(root->val);
root = root->right;
}else{
stack.push(root);
root = root->left;
}
}
return ret;
}
};
20 milli secs.
方法三:以上两种方法都需要O(n)的栈空间,下面的方法能够用O(1)的空间实现遍历。
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ret;
stack<TreeNode*> stack;
TreeNode* cur = root;
TreeNode* prev = NULL;
while(cur != NULL)
{
if(cur->left == NULL){
ret.push_back(cur->val);
cur = cur->right;
}else{
prev = cur->left;
if(prev != NULL){
while(prev->right != NULL && prev->right != cur)
prev = prev->right;
}
if(prev->right == cur){
prev->right == NULL;
ret.push_back(cur->val);
cur = cur->right;
}else{
prev->right = cur;
cur = cur->left;
}
}
}
return ret;
}
};