您的位置:首页 > 其它

LintCode 二叉树的遍历 (非递归)

2015-07-01 14:48 323 查看
前序:

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
stack<TreeNode*> s;
vector<int> res;
while (root!= nullptr || !s.empty()) {
while (root != nullptr) {
res.push_back(root->val);
s.push(root);
root = root->left;
}
if (!s.empty()) {
root = s.top();
s.pop();
root = root->right;
}
}
return res;
}
};


中序:

class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
stack<TreeNode *> s;
vector<int> res;
while (root!=nullptr || !s.empty()) {
while (root != nullptr){
s.push(root);
root = root->left;
}
if (!s.empty()) {
root = s.top();
res.push_back(root->val);
s.pop();
root = root ->right;
}
}
return res;
}
};


后续:

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> res;
stack<TreeNode*> s;
TreeNode * cur;
TreeNode *pre = nullptr;
if (root == nullptr) {
return res;
}
s.push(root);
while (!s.empty()) {
cur = s.top();
if ((cur->left == nullptr && cur->right == nullptr) || (pre != nullptr && (pre==cur->left || pre == cur->right))) {
res.push_back(cur->val);
s.pop();
pre = cur;
}
else {
if (cur->right != nullptr) {
s.push(cur->right);
}
if (cur->left != nullptr) {
s.push(cur->left);
}
}
}
return res;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: