From d9a73a9121b9d10707b418e6d2f79299fecb3c26 Mon Sep 17 00:00:00 2001 From: ductnn Date: Tue, 16 Apr 2024 20:16:00 +0700 Subject: [PATCH] add sol --- leetcode/623.AddOneRowtoTree/sol.go | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 leetcode/623.AddOneRowtoTree/sol.go diff --git a/leetcode/623.AddOneRowtoTree/sol.go b/leetcode/623.AddOneRowtoTree/sol.go new file mode 100644 index 0000000..538a09a --- /dev/null +++ b/leetcode/623.AddOneRowtoTree/sol.go @@ -0,0 +1,44 @@ +// 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 + * } + */ + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func addOneRow(root *TreeNode, val int, depth int) *TreeNode { + if depth == 1 { + return &TreeNode{val, root, nil} + } + q := []*TreeNode{root} + i := 0 + for len(q) > 0 { + i++ + for k := len(q); k > 0; k-- { + node := q[0] + q = q[1:] + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + if i == depth-1 { + node.Left = &TreeNode{val, node.Left, nil} + node.Right = &TreeNode{val, nil, node.Right} + } + } + } + return root +}