Problem solving/Algorithms
[LeetCode] 125. Same Tree (C#)
Young_A
2024. 1. 12. 09:44
LeetCode - Problems - Algorithms - 125. Same Tree
Same Tree - LeetCode
Can you solve this real interview question? 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
leetcode.com
My Solution (C#)
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsSameTree(TreeNode p, TreeNode q) {
//time complexcity O(p+q)
//comparing nulls and/or singles //only comparing nulls
if (p == null && q == null) return true;
if (p == null || q == null) return false;
//first thing to check (root)
if (p.val != q.val){ return false;}
//comparing lower level //left and right both
//recursively continue lower and lower
//until node is not equal => false
//or/and node is null =>true
return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);
}
}