個人練習之二叉樹的前序遍歷

Kuroba_thief發表於2020-11-17

leet_code.二叉樹的前序遍歷

Answer 1:使用棧

/**
 * 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) {
        vector<int> ret;
        stack<TreeNode*> s;

        TreeNode* tmp = root;
        while(!s.empty() || tmp){
            if(tmp){
                ret.push_back(tmp->val);
                s.push(tmp);
                tmp = tmp->left;
            }else{
                tmp = s.top();
                s.pop();
                tmp = tmp->right;
            }
        }
        return ret;
    }
};

 

相關文章