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

Leetcode Binary Tree Preorder Traversal

时间:2015-10-23 16:03:48      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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

标签:

原文地址:http://www.cnblogs.com/mengfanrong/p/4904578.html

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