Created
October 5, 2022 10:31
-
-
Save dluciano/f96d9530264c82f2c5ea8b5cc73dcb65 to your computer and use it in GitHub Desktop.
623. Add One Row to Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public TreeNode AddOneRow(TreeNode root, int val, int depth) { | |
if(depth == 1){ | |
var tempLeft = root; | |
root = new TreeNode(val); | |
root.left = tempLeft; | |
return root; | |
} | |
var queue = new Queue<TreeNode>(); | |
queue.Enqueue(root); | |
var currentDepth = 1; | |
while(queue.Count > 0 && currentDepth < depth){ | |
var sz = queue.Count; | |
while(sz > 0){ | |
var current = queue.Dequeue(); | |
sz--; | |
if(currentDepth == depth - 1){ | |
var tempLeft = current.left; | |
var tempRight = current.right; | |
current.left = new TreeNode(val); | |
current.right = new TreeNode(val); | |
current.left.left = tempLeft; | |
current.right.right = tempRight; | |
continue; | |
} | |
if(current.left is not null) | |
queue.Enqueue(current.left); | |
if(current.right is not null) | |
queue.Enqueue(current.right); | |
} | |
currentDepth++; | |
} | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment