关于《代码随想录》中的一些思路的探讨

 

 这里提到使用返回值为新加入的节点进行父子关系赋值,我觉得既然是二叉树那么递归就得从三种遍历方式中选择一种出来,不能两次递归然后使用返回值就结束了,不符合第一眼看到题目的思路。

我的代码如下:

/**
 * 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:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* ret = new TreeNode();
        if(root == nullptr){
            ret->val = val;
            return ret;
        }
        if(val > root->val && root->right==nullptr){
            root->right = new TreeNode(val);
            return root;
        }

        if(val < root->val && root->left == nullptr){
            root->left = new TreeNode(val);
            return root;
        }
        if(root->val < val){
            insertIntoBST(root->right,val);
        }
        if(root->val > val){
            insertIntoBST(root->left,val);
        }

        return root;
    }
};

 

posted @ 2022-12-09 08:21  heisse  阅读(15)  评论(0编辑  收藏  举报