二叉樹遍歷算法,前序

/**
 * 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> rvl;
        if(root == NULL) return rvl;
        stack<TreeNode*> sck;
        sck.push(root);
        while(!sck.empty()){
            TreeNode *node = sck.top();
            sck.pop();
            rvl.push_back(node->val);
            if(node->right != NULL) sck.push(node->right);
            if(node->left != NULL) sck.push(node->left);
        }
        return rvl;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章