当前位置:网站首页>623. Add a row to a binary tree
623. Add a row to a binary tree
2022-08-06 05:02:00 【happykoi】
623. Add a row to the binary tree
Date: 2022/8/5
Title description: Given a binary tree root root and two integers val and depth , add a node row with value val at the given depth depth .
Note that the root node root is at depth 1 .
The addition rules are as follows:
Given an integer depth, for each non-empty tree node cur of depth - 1, create two tree nodes of value val as the left and right sub-roots of cur .
cur The original left subtree should be the left subtree of the root of the new left subtree.
cur The original right subtree should be the right subtree of the root of the new right subtree.
If depth == 1 means that depth - 1 has no depth at all, then create a tree node with value val as the new root of the entire original tree, which is the left subtree of the new root.
Example:
Input: root = [4,2,6,3,1,5], val = 1, depth = 2Output: [4,1,1,2,null,null,6,3,1,5]Input: root = [4,2,null,3,1], val = 1, depth = 3Output: [4,2,null,1,1,3,null,null,1]Thinking:
dfs, continue to traverse if the corresponding depth is not traversed, and connect when traversedCode + Analysis:
class Solution {public:TreeNode* addOneRow(TreeNode* root, int val, int depth) {if(depth == 1){TreeNode* node = new TreeNode(val,root,nullptr);return node;}dfs(root,depth,1,val);return root;}void dfs(TreeNode* root,int depth,int floor,int val){if(root == nullptr) return;if(floor+1 == depth){TreeNode* leftNode = new TreeNode(val,root->left,nullptr);TreeNode* rightNode = new TreeNode(val,nullptr,root->right);root->left = leftNode;root->right = rightNode;return;}//else if(floor < depth-1)dfs(root->left,depth,floor+1,val);dfs(root->right,depth,floor+1,val);}};边栏推荐
- Discrete mathematics the final problem
- Cloudflare CDN(泛播)支持转发的网络端口
- Responsive dream weaving template enterprise group website
- 2023年第六届先进控制,自动化与机器人国际会议(ICACAR 2023)
- MySQL - MySQL 常用存储引擎简介
- $nextTick 原理及作用
- 牛客题目——买卖股票的最好时机(一)、(二)、(三)、设计LRU缓存结构
- 重发布中的路由策略:
- 2023 6th International Conference on Advanced Control, Automation and Robotics (ICACAR 2023)
- LoRa技术有哪些应用场景?
猜你喜欢
随机推荐
旁路缓存策略的缓存一致性问题?
go mod why
工业机器人复习题
“模组+天线”全栈解决方案,提速物联网终端高效部署
牛刀小试基本语法,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang基本语法和变量的使用EP02
Routing policy in redistribution:
OSPF —— cost值选路
牛客题目——买卖股票的最好时机(一)、(二)、(三)、设计LRU缓存结构
2023年第六届数据挖掘与知识发现国际会议(DMKD 2023)
MySQL - 事务四大特性、事务隔离级别、事务的脏读、不可重复读、幻读
egg框架的使用
dedecms采集选择内容模型显示完整
关于STL模板类自定义内存分配器
bahir-flink
如何设置跨域隔离启用 SharedArrayBuffer
Backup and restore Etcd data in a Kubernetes cluster
《 公共关系学 》综合复习资料
Django用orm修改mysql数据库运行出现错误
离散信源最大熵定理的Matlab实现
响应式织梦模板金属丝网类网站








![[Semantic Segmentation] 2019-CCNet ICCV](/img/bf/e718d8c41b064ced085290c49f9565.png)
