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

Binary Tree Preorder Traversal

时间:2015-08-20 22:18:26      阅读:179      评论: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) {}
 * };
 */
class Solution {
private:
      vector<int> res;
public:
    void getOrder(TreeNode* node)
    {
        if(node==NULL)
            return ;
        else
        {
            res.push_back(node->val);
            getOrder(node->left);
            getOrder(node->right);
        }
        return ;
    }
    vector<int> preorderTraversal(TreeNode* root) {
        if(root==NULL)
            return res;
        res.push_back(root->val);
        getOrder(root->left);
        getOrder(root->right);
        return res;
        
    }
};

  但是题目要求用迭代来做。

迭代的代码如下:

 

/**
 * Definition for a binary tree node.
 * 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*> stk;
        while(root!=NULL||!stk.empty())
        {
           if(root!=NULL)
           {
               res.push_back(root->val);
               stk.push(root);
               root=root->left;
           }
           else
           {
               root=stk.top()->right;
               stk.pop();
           }
            
        }
        return res;
    }
};

  

Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4746221.html

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