Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
Approach #0: Iterative
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseList(head *ListNode) *ListNode {if head ==nil {returnnil } cur := headvar prev *ListNodefor cur.Next !=nil { next := cur.Next cur.Next = prev prev = cur cur = next } cur.Next = prevreturn cur}
Approach #1: Recursive
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseList(head *ListNode) *ListNode {if head ==nil {return head }returnreverse(head, nil)}funcreverse(cur, prev *ListNode) *ListNode { next := cur.Next cur.Next = previf next ==nil {return cur } else {returnreverse(next, cur) }}
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 100].
0 <= Node.val < 100
Solution
Approach #0: BFS
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisUnivalTree(root *TreeNode) bool { queue := []*TreeNode{root} v := root.Valfor i :=0; i <len(queue); i++ {if queue[i].Val != v {returnfalse }if queue[i].Left !=nil { queue =append(queue, queue[i].Left) }if queue[i].Right !=nil { queue =append(queue, queue[i].Right) } }returntrue}
Approach #1: DFS
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisUnivalTree(root *TreeNode) bool {if root ==nil {returntrue }if root.Left !=nil&& root.Val != root.Left.Val ||!isUnivalTree(root.Left) {returnfalse }if root.Right !=nil&& root.Val != root.Right.Val ||!isUnivalTree(root.Right) {returnfalse }returntrue}