Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active April 16, 2024 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/beb11f9bb9b835c294a728462f5cfc8a to your computer and use it in GitHub Desktop.
Save lbvf50mobile/beb11f9bb9b835c294a728462f5cfc8a to your computer and use it in GitHub Desktop.
Leetcode: 623. Add One Row to Tree.
// Leetcode: 623. Add One Row to Tree.
// https://leetcode.com/problems/add-one-row-to-tree/
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func addOneRow(root *TreeNode, val int, depth int) *TreeNode {
if 1 == depth {
return &TreeNode{val, root, nil}
}
totalDepth := getDepth(root, 0)
var q1 []*TreeNode
var q2 []*TreeNode
q1 = make([]*TreeNode, 0)
q1 = append(q1, root)
for i := 1; 0 != len(q1); i += 1 {
q2 = make([]*TreeNode, 0)
if i+1 == depth {
for _, v := range q1 {
if i+1 > totalDepth {
tmpL := &TreeNode{val, nil, nil}
tmpR := &TreeNode{val, nil, nil}
v.Left = tmpL
v.Right = tmpR
} else {
if nil != v.Left {
tmp := &TreeNode{val, nil, nil}
tmp.Left = v.Left
v.Left = tmp
q2 = append(q2, tmp)
}
if nil != v.Right {
tmp := &TreeNode{val, nil, nil}
tmp.Right = v.Right
v.Right = tmp // <==== Here.
q2 = append(q2, tmp)
}
}
}
} else {
for _, v := range q1 {
if nil != v.Left {
q2 = append(q2, v.Left)
}
if nil != v.Right {
q2 = append(q2, v.Right)
}
}
}
q1 = q2
q2 = nil
}
return root
}
func getDepth(x *TreeNode, depth int) int {
if nil == x {
return depth
}
a := getDepth(x.Left, depth+1)
b := getDepth(x.Right, depth+1)
if a > b {
return a
} else {
return b
}
}
// Leetcode: 623. Add One Row to Tree.
// https://leetcode.com/problems/add-one-row-to-tree/
// = = = = = = = = = = = = = =
// Accepted.
// Thanks God, Jesus Christ!
// = = = = = = = = = = = = = =
// Runtime: 5 ms, faster than 55.17% of Go online submissions for Add One Row
// to Tree.
// Memory Usage: 5.8 MB, less than 100.00% of Go online submissions for Add
// One Row to Tree.
// 2024.04.16 Dayily Challange, copied from 2022.10.06.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func addOneRow(root *TreeNode, val int, depth int) *TreeNode {
if 1 == depth {
el := &TreeNode{Val: val, Left: root, Right: nil}
return el
}
root.Left = rec(root.Left, val, depth-1, 'l')
root.Right = rec(root.Right, val, depth-1,'r')
return root
}
func rec(x *TreeNode, val int, d int, side int) *TreeNode{
if d < 1 { return x}
if 1 == d {
el := &TreeNode{Val: val, Left: nil, Right: nil}
if 'l' == side {
el.Left = x
}
if 'r' == side{
el.Right = x
}
return el
}
if nil == x { return x}
x.Left = rec(x.Left, val, d-1, 'l')
x.Right = rec(x.Right, val, d-1, 'r')
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment