牛客网刷题-----树

1 如何建立一个二叉树

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

2 前序遍历

/**
 * 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 res;
    void helper(TreeNode* root) {
        if (root == NULL) return ;
        res.push_back(root->val);
        helper(root->left);
        helper(root->right);
    }
     
    vector preorderTraversal(TreeNode *root) {
        helper(root);
        return res;
    }
};
class Solution {
public:
    vector preorderTraversal(TreeNode *root) {
        vector res;
        stack s;
        if (root == NULL){
            return res;
        }
        s.push(root);
        while (!s.empty()){
            TreeNode *cur = s.top();
            s.pop();
            res.push_back(cur->val);
            if (cur->right!=NULL)
                s.push(cur->right);
            if (cur->left!=NULL)
                s.push(cur->left);
        }
        return res;
    }
};

你可能感兴趣的:(刷题算法)