数据结构珠玑——二叉树(1)

数据结构珠玑——二叉树(1)

https://leetcode-cn.com/problems/binary-tree-preorder-traversal

本代码全网最快,100%几乎完全不是运气。

/**
 * 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:
    void preorder(TreeNode* root, vector<int>& traversal)
    {
        if(root)
        {
            traversal.emplace_back(root->val);
            preorder(root->left, traversal);
            preorder(root->right, traversal);
        }
        else return;
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> traversal;
        preorder(root, traversal);
        return traversal;
    }
};

这个代码我觉得没必要讲了,但是中间确实有几部分和传统做法不同,从而比大多做法大幅提高了性能。

https://leetcode-cn.com/problems/binary-tree-inorder-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:
    void inorder(TreeNode* root, vector<int>& traversal)
    {
        if (root)
        {
            inorder(root->left, traversal);
            traversal.emplace_back(root->val);
            inorder(root->right, traversal);
        } else return;
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> traversal;
        inorder(root, traversal);
        return traversal;
    }
};

https://leetcode-cn.com/problems/binary-tree-postorder-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:
    void postorder(TreeNode* root, vector<int>& traversal)
    {
        if (root)
        {
            postorder(root->left, traversal);
            postorder(root->right, traversal);
            traversal.emplace_back(root->val);
        } else return;
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> traversal;
        postorder(root, traversal);
        return traversal;
    }
};
posted @ 2021-12-09 20:10  千心  阅读(34)  评论(0编辑  收藏  举报