当前位置:网站首页>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);}};边栏推荐
猜你喜欢
随机推荐
2022年国外受欢迎的海外社交平台排行榜!
2.cuBLAS开发指南中文版--使用cuBLAS API
Routing policy in redistribution:
MySQL - 事务四大特性、事务隔离级别、事务的脏读、不可重复读、幻读
数据库系统原理与应用教程(078)—— MySQL 练习题:操作题 173-180(二十二):综合练习
Flink-cdc synchronizes mysql data
Comprehensive review materials for "Public Relations"
SequoiaDB分布式数据库2022.7月刊
离散信源最大熵定理的Matlab实现
bahir-flink
boost::asio::async_read、boost::asio::async_write 模板函数的简化版实现逻辑。
"Module + antenna" full stack solution, to speed up the Internet of things terminal efficient deployment
[Semantic Segmentation] 2019-CCNet ICCV
5. redux
The difference between defineProperty and proxy
《论文阅读》EmpTransfo: A Multi-head Transformer Architecture for Creating Empathetic Dialog Systems
aws篇8
Flink-cdc 同步mysql数据
js implements that the array is divided into a new array of groups of 5 objects
3.cuBLAS开发指南中文版--cuBLAS数据类型引用









