100. 相同的树

题目:

思路:

【1】思路参考  剑指 Offer 28. 对称的二叉树(101. 对称二叉树) 这篇,因为比较对称也是比较两颗子树是否一样。

代码展示:

//时间0 ms 击败 100%
//内存38.8 MB 击败 69.97%
/**
 * 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;
 *     }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null || q == null) return (p == null && q == null);
        if (p.val != q.val) return false;
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

 

posted @ 2023-07-07 14:27  忧愁的chafry  阅读(2)  评论(0编辑  收藏  举报