Welcome to Subscribe On Youtube

100. Same Tree

Description

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.

 

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

 

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 104

Solutions

Solution 1: DFS

We can use the DFS recursive method to solve this problem.

First, determine whether the root nodes of the two binary trees are the same. If both root nodes are null, then the two binary trees are the same. If only one of the root nodes is null, then the two binary trees are definitely different. If both root nodes are not null, then determine whether their values are the same. If they are not the same, then the two binary trees are definitely different. If they are the same, then determine whether the left subtrees of the two binary trees are the same and whether the right subtrees are the same. The two binary trees are the same only when all the above conditions are met.

The time complexity is $O(\min(m, n))$, and the space complexity is $O(\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of layers of recursive calls, which will not exceed the number of nodes in the smaller binary tree.

Solution 2: BFS

We can also use the BFS iterative method to solve this problem.

First, add the root nodes of the two binary trees to two queues. Each time, take out one node from each of the two queues and perform the following comparison operations. If the values of the two nodes are not the same, then the structures of the two binary trees are definitely different. If the values of the two nodes are the same, then determine whether the child nodes of the two nodes are null. If only the left child node of one node is null, then the structures of the two binary trees are definitely different. If only the right child node of one node is null, then the structures of the two binary trees are definitely different. If the structures of the left and right child nodes are the same, then add the left and right child nodes of the two nodes to the two queues respectively. For the next iteration, take out one node from each of the two queues for comparison. When both queues are empty at the same time, it means that we have compared all the nodes, and the structures of the two binary trees are completely the same.

The time complexity is $O(\min(m, n))$, and the space complexity is $O(\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of elements in the queue, which will not exceed the number of nodes in the smaller binary tree.

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    
    public class Same_Tree {
    
        /**
         * Definition for a binary tree node.
         * public class TreeNode {
         * int val;
         * TreeNode left;
         * TreeNode right;
         * TreeNode(int x) { val = x; }
         * }
         */
    
        public class Solution_iteration {
            public boolean isSameTree(TreeNode p, TreeNode q) {
                if (p == null) {
                    return q == null;
                }
    
                if (q == null) {
                    return p == null;
                }
    
                Stack<TreeNode> sk1 = new Stack<TreeNode>();
                Stack<TreeNode> sk2 = new Stack<TreeNode>();
    
                sk1.push(p);
                sk2.push(q);
    
                while (!sk1.isEmpty() && !sk2.isEmpty()) {
                    TreeNode current1 = sk1.pop();
                    TreeNode current2 = sk2.pop();
    
                    if (current1 == null && current2 == null) {
                        continue; // @note: missed both null check
                    } else if (current1 == null && current2 != null) {
                        return false;
                    } else if (current1 != null && current2 == null) {
                        return false;
                    } else if (current1.val != current2.val) {
                        return false;
                    }
    
                    sk1.push(current1.left);
                    sk2.push(current2.left);
    
                    sk1.push(current1.right);
                    sk2.push(current2.right);
    
                }
    
                // final check
                if (!sk1.isEmpty() || !sk2.isEmpty()) {
                    return false;
                }
    
                return true;
    
            }
        }
    
    
        public class Solution_recursion {
            public boolean isSameTree(TreeNode p, TreeNode q) {
    
                if (p == null) {
                    return q == null;
                }
    
                if (q == null) {
                    return p == null;
                }
    
                if (p.val != q.val) {
                    return false;
                }
    
                return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
            }
        }
    
    }
    
    //////
    
    class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if (p == q) return true;
            if (p == null || q == null || p.val != q.val) return false;
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
    }
    
  • /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        bool isSameTree(TreeNode* p, TreeNode* q) {
            if (p == q) return true;
            if (!p || !q || p->val != q->val) return false;
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
      def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if not p or not q:
          return p == q # covers: p=none and q!=none, q=none and p!=none, both none
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
    
    
    # iteration
    class Solution:
        def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
            if p is None:
                return q is None
    
            if q is None:
                return p is None
    
            stack1 = [p]
            stack2 = [q]
    
            while stack1 and stack2:
                current1 = stack1.pop()
                current2 = stack2.pop()
    
                if current1 is None and current2 is None:
                    continue
                elif current1 is None or current2 is None:
                    return False
                elif current1.val != current2.val:
                    return False
    
                stack1.append(current1.left)
                stack2.append(current2.left)
    
                stack1.append(current1.right)
                stack2.append(current2.right)
    
            return not stack1 and not stack2
    
    
  • /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func isSameTree(p *TreeNode, q *TreeNode) bool {
    	if p == q {
    		return true
    	}
    	if p == nil || q == nil || p.Val != q.Val {
    		return false
    	}
    	return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
    }
    
  • /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     val: number
     *     left: TreeNode | null
     *     right: TreeNode | null
     *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.left = (left===undefined ? null : left)
     *         this.right = (right===undefined ? null : right)
     *     }
     * }
     */
    
    function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null || p.val !== q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
    
    
  • /**
     * 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) {
        if (!p && !q) return true;
        if (p && q) {
            return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
        return false;
    };
    
    
  • /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     public $val = null;
     *     public $left = null;
     *     public $right = null;
     *     function __construct($val = 0, $left = null, $right = null) {
     *         $this->val = $val;
     *         $this->left = $left;
     *         $this->right = $right;
     *     }
     * }
     */
    class Solution {
        /**
         * @param TreeNode $p
         * @param TreeNode $q
         * @return Boolean
         */
        function isSameTree($p, $q) {
            if ($p == null && $q == null) {
                return true;
            }
            if ($p == null || $q == null) {
                return false;
            }
            if ($p->val != $q->val) {
                return false;
            }
            return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right);
        }
    }
    
  • // Definition for a binary tree node.
    // #[derive(Debug, PartialEq, Eq)]
    // pub struct TreeNode {
    //   pub val: i32,
    //   pub left: Option<Rc<RefCell<TreeNode>>>,
    //   pub right: Option<Rc<RefCell<TreeNode>>>,
    // }
    //
    // impl TreeNode {
    //   #[inline]
    //   pub fn new(val: i32) -> Self {
    //     TreeNode {
    //       val,
    //       left: None,
    //       right: None
    //     }
    //   }
    // }
    use std::rc::Rc;
    use std::cell::RefCell;
    impl Solution {
        fn dfs(p: &Option<Rc<RefCell<TreeNode>>>, q: &Option<Rc<RefCell<TreeNode>>>) -> bool {
            if p.is_none() && q.is_none() {
                return true;
            }
            if p.is_none() || q.is_none() {
                return false;
            }
            let r1 = p.as_ref().unwrap().borrow();
            let r2 = q.as_ref().unwrap().borrow();
            r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right)
        }
    
        pub fn is_same_tree(
            p: Option<Rc<RefCell<TreeNode>>>,
            q: Option<Rc<RefCell<TreeNode>>>
        ) -> bool {
            Self::dfs(&p, &q)
        }
    }
    
    

All Problems

All Solutions