二叉搜索树的插入,只要到规定的节点位置新建一个叶节点就可以了。
#include#include #include using namespace std; 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* ans = new TreeNode(val); if (root == nullptr)return ans; TreeNode* p = root; while (p != nullptr) { if (val < p->val) { if (p->left == nullptr) { p->left = ans; break; } else p = p->left; } else { if (p->right == nullptr) { p->right = ans; break; } else p = p->right; } } return root; } }; void print(TreeNode* a) { if(a != nullptr){ cout << a->val; print(a->left); print(a->right); } } int main() { Solution test; TreeNode* c = new TreeNode(1); TreeNode* b = new TreeNode(3); TreeNode* a = new TreeNode(2,c, b); print(test.insertIntoBST(a, 5)); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)