關於《程式碼隨想錄》中的一些思路的探討
阿新 • • 發佈:2022-12-09
這裡提到使用返回值為新加入的節點進行父子關係賦值,我覺得既然是二叉樹那麼遞迴就得從三種遍歷方式中選擇一種出來,不能兩次遞迴然後使用返回值就結束了,不符合第一眼看到題目的思路。
我的程式碼如下:
/**
* 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;
}
};