/**
* 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> preorderTraversal(TreeNode *root) {
vector<int> ret;
if(root==NULL)
return ret;
std::stack<TreeNode*> ss;
ss.push(root);
TreeNode* node;
while(ss.size()>0)
{
node = ss.top();
ss.pop();
ret.push_back(node->val);
if(node->right)
ss.push(node->right);
if(node->left)
ss.push(node->left);
}
return ret;
}
};
Showing posts with label Binary Tree. Show all posts
Showing posts with label Binary Tree. Show all posts
Thursday, January 23, 2014
[LeetCode] Binary Tree Preorder Traversal
[LeetCode] Binary Tree Postorder Traversal
/**
* 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> postorderTraversal(TreeNode *root) {
vector<int> ret;
if(root==NULL)
return ret;
TreeNode* current;
stack<TreeNode*> s;
s.push(root);
while(s.size()>0)
{
current = s.top();
s.pop();
if(current==NULL)
{
current = s.top();
s.pop();
ret.push_back(current->val);
continue;
}
s.push(current);
s.push(NULL);
if(current->right)
s.push(current->right);
if(current->left)
s.push(current->left);
}
return ret;
}
};
Subscribe to:
Posts (Atom)