首页 > 代码库 > Leetcode Binary Tree Preorder Traversal

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