Same Tree
You get the roots of two binary trees, p and q. Say whether they are the same tree: the same shape, with the same value in every matching place. Our trees: both are 5 with children 8 and 6; in p, 6 has a left child 4, in q, 6 has a right child 4 — the answer is false: the values are the same, but 4 sits on different sides.
- input
pandq: two binary trees, each written as on LeetCode: its values level by level, left to right,nullfor a missing child.- returns
trueif they are the same: the same shape and the same value in every node; otherwisefalse.- constraints
- 0 ≤ the number of nodes in each tree ≤ 100
- −10⁴ ≤ Node.val ≤ 10⁴
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
function isSameTree(p, q) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more depth-first search (dfs) problems
- 104Maximum Depth of Binary TreeEasysolve
- 226Invert Binary TreeEasysolve
- 101Symmetric TreeEasysolve
- 112Path SumEasysolve
- 200Number of IslandsMediumsolve
- 695Max Area of IslandMediumsolve
- 133Clone GraphMediumsolve
- 417Pacific Atlantic Water FlowMediumsolve
- 129Sum Root to Leaf NumbersMediumsolve
- 222Count Complete Tree NodesMediumsolve
- 236Lowest Common Ancestor of a Binary TreeMediumsolve
- 130Surrounded RegionsMediumsolve
- 399Evaluate DivisionMediumsolve
- 124Binary Tree Maximum Path SumHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.