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

Binary Tree Preorder Traversal (非递归实现)

时间:2014-11-10 11:47:59      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   for   

具体思路参见:二叉树的非递归遍历(转)

/**
 * 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> res;
        stack<TreeNode*> s;
        while (root!=NULL||!s.empty())
        {
            while (root!=NULL)
            {
                res.push_back(root->val);
                s.push(root);
                root=root->left;
            }
            if(root==NULL)
       { root
=s.top(); root=root->right; s.pop(); } } return res; } };

 

Binary Tree Preorder Traversal (非递归实现)

标签:style   blog   http   io   color   ar   os   sp   for   

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

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