Skip to content

Commit 84c50fe

Browse files
Merge pull request #589 from Aratrik-02/branch-Aratrik
Added a code on binary trees in C++
2 parents 0ab2793 + 8323b19 commit 84c50fe

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Trees/addOneRowToTree.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
3+
623. Add One Row to Tree
4+
Problem Link: https://leetcode.com/problems/add-one-row-to-tree/description/
5+
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
6+
7+
Note that the root node is at depth 1.
8+
9+
The adding rule is:
10+
11+
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
12+
cur's original left subtree should be the left subtree of the new left subtree root.
13+
cur's original right subtree should be the right subtree of the new right subtree root.
14+
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
15+
16+
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
17+
Output: [4,1,1,2,null,null,6,3,1,5]
18+
19+
Input: root = [4,2,null,3,1], val = 1, depth = 3
20+
Output: [4,2,null,1,1,3,null,null,1]
21+
22+
*/
23+
24+
/**
25+
* Definition for a binary tree node.
26+
* struct TreeNode {
27+
* int val;
28+
* TreeNode *left;
29+
* TreeNode *right;
30+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
31+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
32+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
33+
* };
34+
*/
35+
class Solution {
36+
public:
37+
void dfs(TreeNode* root, int val, int depth,int k){
38+
if(!root)return;
39+
if(depth==k+1){
40+
TreeNode *templ=new TreeNode(val);
41+
TreeNode *l=root->left;
42+
root->left=templ;
43+
templ->left=l;
44+
TreeNode *tempr=new TreeNode(val);
45+
TreeNode *r=root->right;
46+
root->right=tempr;
47+
tempr->right=r;
48+
}
49+
dfs(root->left,val,depth,k+1);
50+
dfs(root->right,val,depth,k+1);
51+
return;
52+
}
53+
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
54+
if(depth==1){
55+
TreeNode *temp=new TreeNode(val);
56+
temp->left=root;
57+
return temp;
58+
}
59+
dfs(root,val,depth,1);
60+
return root;
61+
}
62+
};

0 commit comments

Comments
 (0)