Hyoseo Lee
01 Index 02 Current page Writing 03 Work 04 Notes 05 Games 06 Author
leetcode

100. Same Tree

Topic Depth-First Search
Area Data Structures
Summary
two trees are identical when their values and two childs are identical. we can use reculsion for that easily.

Problem

View on LeetCode →

Difficulty: Easy
Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree

Intuition

it was easy. just use recursion.

Approach

two trees are identical when their values and two childs are identical. we can use reculsion for that easily.

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(!p && !q){
        return true;
    }
    else if(!p || !q){
        return false;
    }
    else{
        return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
}

Complexity

  • Time: O(n)O(n)

  • Space: O(n)O(n)

Thoughts

Too easy for me now.