建设网站存在的问题,邢台seo外包,超级外链吧,北京广告公司标牌制作文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析#xff1a;这道题关键在于分析插入值的位置#xff0c;不论插入的值是什么#xff08;插入值和原有树中的键值都… 文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析这道题关键在于分析插入值的位置不论插入的值是什么插入值和原有树中的键值都不相等最终都是在空节点的位置插入那么我们就可以确定递归的终止条件为空节点。因此只要和中间节点比较键值确定递归是左子树还是右子树递归完成后返回根节点。 程序如下
class Solution {
public: TreeNode* insertIntoBST(TreeNode* root, int val) {if (root NULL) {TreeNode* cur new TreeNode(val);return cur;} if (root-val val) root-left insertIntoBST(root-left, val);if (root-val val) root-right insertIntoBST(root-right, val);return root;}
};三、完整代码
# include iostream
# include vector
# include string
# include queue
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) {if (root NULL) {TreeNode* cur new TreeNode(val);return cur;} if (root-val val) root-left insertIntoBST(root-left, val);if (root-val val) root-right insertIntoBST(root-right, val);return root;}
};// 前序遍历迭代法创建二叉树每次迭代将容器首元素弹出弹出代码还可以再优化
void Tree_Generator(vectorstring t, TreeNode* node) {if (!t.size() || t[0] NULL) return; // 退出条件else {node new TreeNode(stoi(t[0].c_str())); // 中if (t.size()) {t.assign(t.begin() 1, t.end());Tree_Generator(t, node-left); // 左}if (t.size()) {t.assign(t.begin() 1, t.end());Tree_Generator(t, node-right); // 右}}
}templatetypename T
void my_print(T v, const string msg)
{cout msg endl;for (class T::iterator it v.begin(); it ! v.end(); it) {cout *it ;}cout endl;
}templateclass T1, class T2
void my_print2(T1 v, const string str) {cout str endl;for (class T1::iterator vit v.begin(); vit v.end(); vit) {for (class T2::iterator it (*vit).begin(); it (*vit).end(); it) {cout *it ;}cout endl;}
}// 层序遍历
vectorvectorint levelOrder(TreeNode* root) {queueTreeNode* que;if (root ! NULL) que.push(root);vectorvectorint result;while (!que.empty()) {int size que.size(); // size必须固定, que.size()是不断变化的vectorint vec;for (int i 0; i size; i) {TreeNode* node que.front();que.pop();vec.push_back(node-val);if (node-left) que.push(node-left);if (node-right) que.push(node-right);}result.push_back(vec);}return result;
}int main()
{// 构建二叉树vectorstring t { 4, 2, 1, NULL, NULL, 3, NULL, NULL, 7, NULL, NULL }; // 前序遍历my_print(t, 目标树);TreeNode* root new TreeNode();Tree_Generator(t, root);vectorvectorint tree levelOrder(root);my_print2vectorvectorint, vectorint(tree, 目标树:);// 插入目标值int val 5;Solution s;TreeNode* result s.insertIntoBST(root, val);vectorvectorint tree1 levelOrder(result);my_print2vectorvectorint, vectorint(tree1, 目标树:);system(pause);return 0;
}end