码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Iterative Traversal

时间:2016-01-29 11:31:25      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

Preorder

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode *> sta;
        sta.push(root);
        while (!sta.empty())
        {
            TreeNode* cur = sta.top();
            sta.pop();
            res.push_back(cur->val);
            if (cur->right) sta.push(cur->right);
            if (cur->left) sta.push(cur->left);
        }
        return res;
    }
};

 

postorder

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode *> sta;
        sta.push(root);
        TreeNode *last = NULL;
        while (!sta.empty())
        {
            TreeNode *cur = sta.top();
            TreeNode *left = cur->left, *right = cur->right;
            if (left && (!last || (last != left && last != right)))
                sta.push(left);
            else if (right && (!last || last != right))
                sta.push(right);
            else
            {
                res.push_back(cur->val);
                last = cur;
                sta.pop();
            }
        }
        return res;
    }
};

inorder

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> sta;
        while(1) {
            while(root) { sta.push(root); root = root->left; }
            if(sta.empty()) break;
            root = sta.top(); sta.pop();
            res.push_back(root->val);
            root = root->right;
        }
        return res;
    }
};

  

Binary Tree Iterative Traversal

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5168073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!