LeetCode 1448. Count Good Nodes in Binary Tree
·
코딩테스트/LeetCode
1448. Count Good Nodes in Binary TreeProblemSolutionThe requirements of this problems are as follows:A node is called good if its value is the largest on the path from the root to that node.Return the number of good nodes.To satifsy these requirments, I used a preorder traversal with a stack. First, initialize stack as a list containing root and root.val and set good as 0.Each element in the sta..
LeetCode 872. Leaf-Similar Trees
·
코딩테스트/LeetCode
872. Leaf-Similar Trees ProblemSolutionThe key requirement of this problem is as follows:Return True if the leaf of sequences of root1 and root2 are the same otherwise return False.To satisfy this requirement, I used a preorder traversal with a stack. Since we need to process two binary trees, I created a helper function getLeaves. First, initialize stack as a list containing root, and set leave..
LeetCode 104. Maximum Depth of Binary Tree
·
코딩테스트/LeetCode
104. Maximum Depth of Binary Tree ProblemSolutionThe key requirement of this problem is as follows:Return the maximum depth of given binary tree.To satisfy this requirement, I used level-order-traversal with a queue. First, it root is None, return 0 because the tree is empty. Initialize value as a list containing root, and set depth to 0. The list value stores all nodes at the current level.When..
LeetCode 2130. Maximum Twin Sum of a Linked List
·
코딩테스트/LeetCode
2130. Maximum Twin Sum of a Linked List ProblemSolutionThe key requirements of this problem are as follows:The linked list has an even legnth.The ith node is paired with the (length-1-i)th node.Return the maximum sum among all twin pairs.To satisfy these requirements, I used a two-pointer approach.First, I split the problem into three steps.Find the middle nodes of the list.Reverse the second ha..
LeetCode 206. Reverse Linked List
·
코딩테스트/LeetCode
206. Reverse Linked ListProblem SolutionThe requirement of this problem is as follows:Return the reversed linked list.To satisfy this problem, I used a two-pointer approach. First, to reverse the list, at least two nodes are nedded.So if head is None or head.next is None, return head directly. In the main logic, I initialize the two pointers prev and ahead.prev starts as None, because the first..
LeetCode 328. Odd Even Linked List
·
코딩테스트/LeetCode
328. Odd Even Linked List Problem SolutionThe key requirements of this problem are as follows:Seperate the linked list into odd and even positions.After seperating them, place the odd group first and then even group after it.Return the reordered list.To satisfy these requirements, I used the two-pointer approach. First, to seperate off and even positions, we need at least two nodes.So if head i..