LeetCode Binary Tree Preorder Traversal

/**
 * 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;
        if (root == NULL) return res; 
        vector<TreeNode*> stack;
        stack.push_back(root);
        while(!stack.empty()){ 
            TreeNode* n = stack.back();
            stack.pop_back();
            res.push_back(n->val);
            if (n->right != NULL) stack.push_back(n->right);
            if (n->left != NULL) stack.push_back(n->left);
        }
    }
};

水一发,非递归通用实现见 LeetCode Binary Tree Inorder Traversal

posted @ 2014-03-21 14:28  卖程序的小歪  阅读(134)  评论(0编辑  收藏  举报