The same tree

Given the root nodes p and q of two binary trees, write a function to check whether the two trees are the same.

Two trees are considered identical if they are structurally identical and the nodes have the same value.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/sa… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution one: recursion

Recursion is used as follows:

  • First, return true if both p and q are null;
  • If only one of p and q is null, return false;
  • Return false if neither p nor q is null, and if the values of p and q are not equal; If the values of p and q are equal, the recursion determines whether the left and right subtrees of p and Q are both equal.

So when I finish the recursion, I get the result.

public class LeetCode_100 {
    public static boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if ((p == null&& q ! =null) || (p ! =null && q == null)) {
            return false;
        }
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    public static void main(String[] args) {
        TreeNode p = new TreeNode(1);
        p.left = new TreeNode(2);
        p.right = new TreeNode(3);

        TreeNode q = new TreeNode(1);
        q.left = new TreeNode(2);
        q.right = new TreeNode(3); System.out.println(isSameTree(p, q)); }}Copy the code

【 Daily Message 】 Do your best in everything, and the result will be fate. Be grateful and content.