注意一下本题不是平衡二叉树,虽然题干中提到可以改变树的形状(平衡二叉树的插入和删除就可能会改变树的形状),所以只要找到树末尾插入位置就 OK 了。
迭代法:
/** * 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) { if(root == NULL) { auto p = new TreeNode(val); return p; } auto p = root; TreeNode* parent = NULL; // 设置parent指针以便后面进行结点插入操作 while(p) { if(val > p->val) { parent = p; p = p->right; } else { parent = p; p = p->left; } } p = new TreeNode(val); if(val > parent->val) { parent->right = p; } else { parent->left = p; } return root; } };
递归法:
/** * 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) { if(root == NULL) { auto p = new TreeNode(val); return p; } // 根据插入的数值决定递归方向 if(root->val > val) root->left = insertIntoBST(root->left, val); if(root->val < val) root->right = insertIntoBST(root->right, val); return root; // 最后返回root,因为上面的递归逻辑给root的分支赋值,这样不破坏原来的树结构 } };