Same Tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// Base case: if both trees are null, they are identical
if (p == null && q == null) {
return true;
}
// If only one tree is null or the values are different, they are not identical
if (p == null || q == null || p.val != q.val) {
return false;
}
// Recursively check if the left and right subtrees are identical
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Related Problems
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).