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

Leetcode Binary Tree Preorder Traversal

时间:2014-10-04 15:07:46      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:io   ar   for   c   on   r   ef   res   as   

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

Leetcode Binary Tree Preorder Traversal

标签:io   ar   for   c   on   r   ef   res   as   

原文地址:http://blog.csdn.net/wyj7260/article/details/39779495

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