Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Last active August 18, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyleaf/edd4c847ed6209741dcb63dd0c1f9b47 to your computer and use it in GitHub Desktop.
Save lyleaf/edd4c847ed6209741dcb63dd0c1f9b47 to your computer and use it in GitHub Desktop.
二叉树的遍历
class Solution {
public:
void inorderTraversalHelper(TreeNode* root, vector<int>& x) {
if (!root) return;
if (root->left) inorderTraversalHelper(root->left,x);
x.push_back(root->val);
if (root->right) inorderTraversalHelper(root->right,x);
}
vector<int> inorderTraversal(TreeNode* root){
vector<int> x;
inorderTraversalHelper(root,x);
return x;
}
};
/**
* 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){
vector<int> x;
stack<TreeNode*> s;
if (root) s.push(root);
TreeNode* current;
while (!s.empty()){
current = s.top();
if (current->left){
s.push(current->left);
current->left = NULL;
}
else {
x.push_back(s.top()->val);
s.pop();
if (current->right) s.push(current->right);
}
}
return x;
}
};
/*
先找到最最左的点,然后每次回溯到一个节点A的时候,都保证这个节点A的左子树已经遍历,后面就只需要遍历A的右子树(同理,又是先找到右子树的最左点)
*/
/**
* 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){
vector<int> x;
stack<TreeNode*> s;
TreeNode* current=root;
while (!s.empty() || current){
if (current != NULL){
s.push(current);
current = current->left;
}
else {
TreeNode* pNode = s.top();
x.push_back(pNode->val);
s.pop();
current = pNode->right;
}
}
return x;
}
};
@lyleaf
Copy link
Author

lyleaf commented Aug 18, 2016

我的naive method,使用了递归。没什么好说的。
Morris Traversal 竟然可以不要Stack.我也是醉了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment