Skip to content

Latest commit

 

History

History
42 lines (37 loc) · 1000 Bytes

144.-binary-tree-preorder-traversal.md

File metadata and controls

42 lines (37 loc) · 1000 Bytes

144. Binary Tree Preorder Traversal

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        // 递归做的就是stack
        
        stack<TreeNode*> s;
        vector<int> ans;
        if (root==nullptr) return ans;
        s.push(root);
        TreeNode* node;
        while (!s.empty()) {
            root = s.top();
            ans.push_back(root->val);
            s.pop();
            if (root->right){
                s.push(root->right);
            }
            if (root->left){
                s.push(root->left);
            }
        }
            
        return ans;
    }
    
};