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

Binary Tree Inorder Traversal

时间:2015-01-23 17:46:36      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the inorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

中序遍历非递归版本

法一:

class Solution {
private:
    vector<int> res;
public:
    vector<int> inorderTraversal(TreeNode *root) {
        res.clear();
        if(root==NULL) return res;
        stack<pair<TreeNode*,bool>> s;
        s.push(make_pair(root,false));
        while (!s.empty())
        {
            root=s.top().first;
            while (root!=NULL&&!s.top().second)
            {
                s.top().second=true;
                root=root->left;
                if(root!=NULL) s.push(make_pair(root,false));
            }
            root=s.top().first->right;
            res.push_back(s.top().first->val);
            s.pop();
            if(root!=NULL)
                s.push(make_pair(root,false));
        }
        return res;
    }
};

 

法二:

class Solution {
private:
    vector<int> res;
public:
    vector<int> inorderTraversal(TreeNode *root) {
        res.clear();
        if(root==NULL) return res;
        stack<pair<TreeNode*,bool>> s;
        TreeNode* t;
        int used;
        s.push(make_pair(root,false));
        while(!s.empty())
        {
            t=s.top().first;
            used = s.top().second;
            s.pop();
            if(!used)
            {
                if(t->right!=NULL) s.push( make_pair(t->right,false));
                s.push(make_pair(t,true));
                if(t->left!=NULL) s.push( make_pair(t->left,false));
            }
            else res.push_back(t->val);
        }
        return res;
    }
};

 

Binary Tree Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/fightformylife/p/4244454.html

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