# 100. Same Tree

{% embed url="<https://leetcode.com/problems/same-tree/>" %}

dfs

> time: O(n)

> space: O(h), worst O(n)

```jsx
var isSameTree = function(p, q) {
    if (p === null && q === null) return true;
    if (p === null || q === null) return false;
    if (p.val !== q.val) return false;

    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
```

iteration

> time: O(n)

> space: O(n), max(p, q) the number of nodes

```jsx
/**
 * 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}
 */
var isSameTree = function(p, q) {
    
    let pq = [p];
    let qq = [q];

    while (pq.length > 0 && qq.length > 0) {
        const currp = pq.shift()
        const currq = qq.shift();

        if (currp !== null && currq !== null) {
            if (currp.val !== currq.val) return false;
        } else if (currp === null && currq === null) {
            continue;
        } else {
            return false;
        }

        pq.push(currp.left);
        pq.push(currp.right);

        qq.push(currq.left);
        qq.push(currq.right);

    }

    return true;
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/100.-same-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
