Problem statement

Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.

Example 1:

Input:
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5 v = 1 d = 2 Output:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5

Example 2:

Input:
A binary tree as following:
4
/
2
/ \
3 1 v = 1 d = 3 Output:
4
/
2
/ \
1 1
/ \
3 1

Note:

  1. The given d is in range [1, maximum depth of the given tree + 1].
  2. The given binary tree has at least one tree node.

Solution

This is the second problem of leetcode weekly contest 37, which is involved with a binary tree. According to what described, obviously, there are two solutions: BFS and DFS.

BFS

This is the BFS problem for a tree, normally, we should get the size of the queue before we process each level, which is different with the BFS in two dimension matrix.

Time complexity is O(n), space complexity is O(n).

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if(d == ){
TreeNode* node = new TreeNode(v);
node->left = root;
return node;
}
queue<TreeNode*> que;
que.push(root);
while(!que.empty() && d > ){
d--;
int size = que.size();
while(size > ){
TreeNode* node = que.front();
que.pop();
if(d == ){
TreeNode* left_node = new TreeNode(v);
left_node->left = node->left;
node->left = left_node;
TreeNode* right_node = new TreeNode(v);
right_node->right = node->right;
node->right = right_node;
} else {
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
size--;
}
}
return root;
}
};

DFS

This is the best solution for this problem, it is

More accurate, this is a divide and conquer problem. We conquer first in current level and divide to lower level.

Time complexity is O(n), space complexity is O(1).

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
// at least one root node, no need do root == NULL test
if(d == ){
TreeNode* dummy = new TreeNode(v);
dummy->left = root;
return dummy;
}
add_node(root, v, d - );
return root;
}
private:
void add_node(TreeNode* node, int val, int depth){
// conquer
if(node == NULL){
return;
}
if(depth == ){
TreeNode* left_node = new TreeNode(val);
left_node->left = node->left;
node->left = left_node;
TreeNode* right_node = new TreeNode(val);
right_node->right = node->right;
node->right = right_node;
return;
}
// divide
add_node(node->left, val, depth - );
add_node(node->right, val, depth - );
return;
}
};

623. Add One Row to Tree的更多相关文章

  1. 【LeetCode】623. Add One Row to Tree 解题报告(Python)

    [LeetCode]623. Add One Row to Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problem ...

  2. [LeetCode] 623. Add One Row to Tree 二叉树中增加一行

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

  3. 【leetcode】623. Add One Row to Tree

    题目如下: Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with ...

  4. [LeetCode] Add One Row to Tree 二叉树中增加一行

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

  5. [Swift]LeetCode623. 在二叉树中增加一行 | Add One Row to Tree

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

  6. [leetcode-623-Add One Row to Tree]

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

  7. 【跟着stackoverflow学Pandas】add one row in a pandas.DataFrame -DataFrame添加行

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  8. add new row to data.frame/dataframe

    df<-NULL new_row<-data.frame(colA="xxx",colB=123) df<-rbind(df,new_row)

  9. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

随机推荐

  1. POJ Washing Clothes 洗衣服 (01背包,微变型)

    题意:有多种颜色的衣服,由两个人合作来洗,必须洗完一种颜色才能洗下一种,求需要多少时间能洗完. 思路:将衣服按颜色分类,对每种颜色进行01背包,容量上限是该种颜色衣服全部洗完的耗时长一半,其实就是在最 ...

  2. MVC视图特性

    在主界面的视图中可以使用viewdata,引用主界面的分布视图界面也可以调用主界面的分部视图,但是分部视图不可以定义viewdata并使用 例子如下: // // GET: /Home/ public ...

  3. 【转】Spring, MyBatis 多数据源的配置和管理

    同一个项目有时会涉及到多个数据库,也就是多数据源.多数据源又可以分为两种情况: 1)两个或多个数据库没有相关性,各自独立,其实这种可以作为两个项目来开发.比如在游戏开发中一个数据库是平台数据库,其它还 ...

  4. Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]

    这是因为我把 [/WEB-INF/dispatcher-servlet.xml]的位置换成了[config/springmvc/dispatcher-servlet.xml] 因此idea在原来的位置 ...

  5. java script DOM BOM

    onclick        当用户点击某个对象时调用的事件句柄.ondblclick     当用户双击某个对象时调用的事件句柄. onfocus        元素获得焦点.            ...

  6. 在64位的linux中运行32位的应用程序

    常规做法,先添加32bit架构: sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install libc6:i3 ...

  7. PAT (Advanced Level) Practise - 1096. Consecutive Factors (20)

    http://www.patest.cn/contests/pat-a-practise/1096 Among all the factors of a positive integer N, the ...

  8. Web服务器☞Apache VS Nginx

    Web服务器☞Apache VS Nginx LZ最近公司有一个项目在Web服务器选型上,在Apache和Nginx之间引起了一些讨论.这两者目前都是业内优秀的web服务器,都实现了HTTP1.1协议 ...

  9. non-JRMP server at remote endpoint

    #在相应的domain的domain.xml文件添加下面红色设置,并重启domain <admin-service system-jmx-connector-name="system& ...

  10. clover 显卡注入功能详细讲解

    13 March 2014   GraphicsInjector功能源于变色龙,不过比变色龙更加灵活,定制性更加强大.Intel的显卡 GMA950, X3100, HD300, HD4000被证实可 ...