[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 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.


给定一个二叉树,根节点为第1层,深度为 1。在其第 d 层追加一行值为 v 的节点。

添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树。

将 N 原先的左子树,连接为新节点 v 的左子树;将 N 原先的右子树,连接为新节点 v 的右子树。

如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树。

示例 1:

输入:
二叉树如下所示:
       4
     /       2     6
   / \   /
  3   1 5   

v = 1

d = 2

输出:
       4
      /      1   1
    /        2       6
  / \     /
 3   1   5

示例 2:

输入:
二叉树如下所示:
      4
     /
    2
   / \
  3   1    

v = 1

d = 3

输出:
      4
     /
    2
   / \
  1   1
 /     \
3       1

注意:

  1. 输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。
  2. 输入的二叉树至少有一个节点。


Runtime: 36 ms

Memory Usage: 20.6 MB

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? {
16         if d == 0 || d == 1
17         {
18             var newRoot:TreeNode? = TreeNode(v)
19             if d == 0
20             {
21                 newRoot!.right = root
22             }
23             else
24             {
25                 newRoot!.left = root
26             }
27             return newRoot
28         }
29         if root != nil && d > 1
30         {
31             root!.left = addOneRow(root!.left, v, d > 2 ? d - 1 : 1)
32             root!.right = addOneRow(root!.right, v, d > 2 ? d - 1 : 0)
33         }
34         return root
35     }
36 }


44ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? {
16         if d == 1 {
17             let newRoot = TreeNode(v)
18             newRoot.left = root
19             return newRoot
20         }
21         helper(root, v, 1, d)
22         return root
23     }
24
25     private func helper(_ root: TreeNode?, _ v: Int, _ d: Int, _ targetD: Int) {
26         guard let root = root else { return }
27         if d == targetD - 1 {
28             let curLeft = root.left
29             let curRight = root.right
30             root.left = TreeNode(v)
31             root.right = TreeNode(v)
32             root.left?.left = curLeft
33             root.right?.right = curRight
34             return
35         }
36         helper(root.left, v, d + 1, targetD)
37         helper(root.right, v, d + 1, targetD)
38     }
39 }


48ms

 1 class Solution {
 2     func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? {
 3         if root == nil {
 4             return nil
 5         }
 6
 7         var root = root
 8         if d == 1 {
 9             let newNode = TreeNode(v)
10             newNode.left = root
11             root = newNode
12
13             return root
14         }
15
16         var nodes = [(root, 1)]
17         while let (node, level) = nodes.popLast(), level < d {
18             if let left = node?.left {
19                 nodes.insert((left, level + 1), at: 0)
20             }
21             if let right = node?.right {
22                 nodes.insert((right, level + 1), at: 0)
23             }
24
25             if level == d - 1 {
26                 let leftNode = TreeNode(v)
27                 leftNode.left = node?.left
28                 node?.left = leftNode
29
30                 let rightNode = TreeNode(v)
31                 rightNode.right = node?.right
32                 node?.right = rightNode
33             }
34
35             if level > d {
36                 break
37             }
38         }
39
40         return root
41     }
42 }


60ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14
15 class Solution {
16     func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? {
17         if d == 1 {
18             var node = TreeNode(v)
19             node.left = root
20             return node
21         }
22
23         var stack = [TreeNode?]()
24         var tempArr = [TreeNode?]()
25         var currLevel = 1
26         stack.append(root)
27         while currLevel != d - 1 {
28             //print("currLevel: \(currLevel) ==============")
29             while !stack.isEmpty {
30                 guard let node = stack.removeLast() else {
31                     continue
32                 }
33                 //print("node: \(node.val)")
34                 if let lNode = node.left {
35                     tempArr.append(lNode)
36                 }
37                 if let rNode = node.right {
38                     tempArr.append(rNode)
39                 }
40             }
41             stack.append(contentsOf: tempArr)
42             tempArr.removeAll()
43             currLevel += 1
44         }
45
46         while !stack.isEmpty {
47             guard let node = stack.removeLast() else {
48                 continue
49             }
50             //print("===== node: \(node.val)")
51             if let lNode = node.left {
52                 var vNode = TreeNode(v)
53                 vNode.left = lNode
54                 node.left = vNode
55             } else {
56                 var vNode = TreeNode(v)
57                 node.left = vNode
58             }
59             if let rNode = node.right {
60                 var vNode = TreeNode(v)
61                 vNode.right = rNode
62                 node.right = vNode
63             } else {
64                 var vNode = TreeNode(v)
65                 node.right = vNode
66             }
67         }
68         return root
69     }
70 }


76ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? {
16         if d == 1 {
17             let node = TreeNode(v)
18             node.left = root
19             return node
20         }
21
22
23         if root == nil {
24             return nil
25         }
26
27         let ans = root
28         traverseAddOneRow(root!, v, d-1)
29         return ans
30     }
31
32     func traverseAddOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) {
33         if root == nil {
34             return
35         }
36
37
38         if d < 1 {
39             return
40         }
41
42         if d == 1 {
43
44             let lastl = root!.left
45             let l = TreeNode(v)
46             root!.left = l
47             l.left = lastl
48
49             let lastr = root!.right
50             let r = TreeNode(v)
51             root!.right = r
52             r.right = lastr
53
54             return
55         }
56         traverseAddOneRow(root!.left, v, d-1)
57         traverseAddOneRow(root!.right, v, d-1)
58     }
59
60 }

原文地址:https://www.cnblogs.com/strengthen/p/10472716.html

时间: 2024-08-03 17:06:59

[Swift]LeetCode623. 在二叉树中增加一行 | Add One Row to Tree的相关文章

Leetcode 623.在二叉树中增加一行

在二叉树中增加一行 给定一个二叉树,根节点为第1层,深度为 1.在其第 d 层追加一行值为 v 的节点. 添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树. 将 N 原先的左子树,连接为新节点 v 的左子树:将 N 原先的右子树,连接为新节点 v 的右子树. 如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树. 示例 2: 注意: 输入的深度值 d 的范围是:[1

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 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-

623. Add One Row to Tree

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 n

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 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-

[Swift Weekly Contest 120]LeetCode979. 在二叉树中分配硬币 | Distribute Coins in Binary Tree

Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total. In one move, we may choose two adjacent nodes and move one coin from one node to another.  (The move may be from parent to child, or

PHP实现单击“添加”按钮增加一行表单项,并将所有内容插入到数据库中

PHP实现单击“添加”按钮增加一行表单项,并将所有内容插入到数据库中 效果图: html+jquery: <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <script language="javascript" type="text/javascript" src=&qu

Add an Item to the New Action 在新建按钮中增加一个条目

In this lesson, you will learn how to add an item to the New Action (NewObjectViewController.NewObjectAction). The Event business class from the Business Class Library will be used. 在本课中,您将学习如何在新建按钮(NewObjectViewController.NewObjectAction)中增加一个新的条目.将

只需手动增加一行代码即可让Laravel4运行在SAE

Github:https://github.com/chariothy/laravel4-sae laravel4-sae 只需手动增加一行代码即可让Laravel4(~4.2)运行在SAE,而且在本地和在SAE开发无需命令切换,自动判断环境并切换配置. 安装 在SAE安装Laravel 在SAE安装Laravel与本地环境安装稍有区别: 在SAE的"应用管理"中新建一个没有代码的应用,比如叫project-name(这里面只是便于举例,实际上SAE不允许用字符'-'): 用svn将其

python3实现在二叉树中找出和为某一值的所有路径

在二叉树中找出和为某一值的所有路径请写一个程序创建一棵二叉树,并按照一定规则,输出二叉树根节点到叶子节点的路径.规则如下:1.从最顶端的根结点,到最下面的叶子节点,计算路径通过的所有节点的和,如果与设置的某一值的相同,那么输出这条路径上的所有节点.2.从根节点遍历树时,请请按照左到右遍历,即优先访问左子树的节点.二叉树创建规则:从上到下一层一层的,按照从左到右的顺序进行构造输入"10,5,12,4,7"值,构造的树如下:1) 102) 10      /    5 3) 10