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

二叉树的三种遍历(非递归)

时间:2016-02-02 23:15:56      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

先定义二叉树:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

 

二叉树的先序遍历(以LeetCode 144.为例):

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>ans;
        stack<TreeNode*>s;
        s.push(root);
        while(!s.empty()){
            TreeNode *u=s.top();
            s.pop();
            if(u==NULL) continue;
            ans.push_back(u->val);
            if(u->right) s.push(u->right);
            if(u->left) s.push(u->left);
        }
        return v;
    }
};

  

二叉树的中序遍历(以LeetCode 94.为例):

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

  

二叉树的后序遍历(以LeetCode 145.为例):

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>ans;
        stack<TreeNode *>s;
        s.push(root);
        while(!s.empty()){
            TreeNode *u=s.top();
            s.pop();
            
            if(u==NULL) continue;
            ans.push_back(u->val);
            s.push(u->left);
            s.push(u->right);
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

  

二叉树的三种遍历(非递归)

标签:

原文地址:http://www.cnblogs.com/20143605--pcx/p/5178682.html

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