File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ func maxDepth( _ root: TreeNode ? ) -> Int {
3+ if root == nil {
4+ return 0
5+ }
6+
7+ var level = 0
8+ var stack : [ ( TreeNode ? , Int ) ] = [ ( root, 1 ) ]
9+
10+ while !stack. isEmpty {
11+ let ( current, count) = stack. removeLast ( )
12+ if current? . left == nil && current? . right == nil {
13+ level = max ( level, count)
14+ }
15+ if let right = current? . right {
16+ stack. append ( ( right, count + 1 ) )
17+ }
18+ if let left = current? . left {
19+ stack. append ( ( left, count + 1 ) )
20+ }
21+ }
22+
23+ return level
24+ }
25+ }
26+
Original file line number Diff line number Diff line change 1+ public class ListNode {
2+ public var val : Int
3+ public var next : ListNode ?
4+ public init ( ) { self . val = 0 ; self . next = nil ; }
5+ public init ( _ val: Int ) { self . val = val; self . next = nil ; }
6+ public init ( _ val: Int , _ next: ListNode ? ) { self . val = val; self . next = next; }
7+ }
8+
9+ class Solution {
10+ func mergeTwoLists( _ list1: ListNode ? , _ list2: ListNode ? ) -> ListNode ? {
11+ guard let list1 = list1 else {
12+ return list2
13+ }
14+ guard let list2 = list2 else {
15+ return list1
16+ }
17+
18+ if list1. val < list2. val {
19+ list1. next = mergeTwoLists ( list1. next, list2)
20+ } else {
21+ list2. next = mergeTwoLists ( list2. next, list1)
22+ }
23+ return list1. val < list2. val ? list1 : list2
24+ }
25+ }
26+
You can’t perform that action at this time.
0 commit comments