美文网首页
leetcode 100

leetcode 100

作者: jsy_hello | 来源:发表于2019-05-07 09:42 被阅读0次

github
个人所有的leetcode题解,都在我的 leetcode-java,欢迎star和共同探讨。
leetcode #100
leetcode第100题,判断两棵树是否相同,两棵树如果长得一样,而且对应位置上的值相同,就定义为两棵树相同。

/*
 * @lc app=leetcode id=100 lang=java
 *
 * [100] Same Tree
 *
 * https://leetcode.com/problems/same-tree/description/
 *
 * algorithms
 * Easy (49.87%)
 * Total Accepted:    370.9K
 * Total Submissions: 743.7K
 * Testcase Example:  '[1,2,3]\n[1,2,3]'
 *
 * Given two binary trees, 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:     1         1
 * ⁠         / \       / \
 * ⁠        2   3     2   3
 *
 * ⁠       [1,2,3],   [1,2,3]
 *
 * Output: true
 *
 *
 * Example 2:
 *
 *
 * Input:     1         1
 * ⁠         /           \
 * ⁠        2             2
 *
 * ⁠       [1,2],     [1,null,2]
 *
 * Output: false
 *
 *
 * Example 3:
 *
 *
 * Input:     1         1
 * ⁠         / \       / \
 * ⁠        2   1     1   2
 *
 * ⁠       [1,2,1],   [1,1,2]
 *
 * Output: false
 *
 *
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    // 思路:看到树,就想到了递归
    // 判断两个树是否相同,就是要判断两个树的所有节点是否相同
    // 就是要对树上相同位置的两个节点做判断,这个时候就是分类讨论
    // 两个节点都为空,则为true,此时本次递归完成,为递归的出口
    // 两个节点都不为空且值相同,也为true,然后就该递归判断该节点的左右节点
    // 剩下的情况也是递归出口,不过返回的是false
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if ((p == null && q == null)) {
            return true;
        } else if (p != null && q != null && p.val == q.val) {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        } else {
            return false;
        }

    }
}

相关文章

  • LeetCode 100. 相同的树 | Python

    100. 相同的树 题目来源:力扣(LeetCode)https://leetcode-cn.com/proble...

  • LeetCode Top 100 高频算法题 07:11. Co

    LeetCode Top 100高频算法题,即LeetCode上最高频的100道求职面试算法题。小编和实验室同学之...

  • LeetCode | 100.相同的树

    这次来写一下 LeetCode 的第 100 题,相同的树。 题目描述 题目直接从 LeetCode 上截图过来,...

  • leetcode 100

    github个人所有的leetcode题解,都在我的 leetcode-java,欢迎star和共同探讨。leet...

  • ARTS-005

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

  • ARTS-003

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

  • ARTS-004

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

  • ARTS-006

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

  • ARTS-007

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

  • ARTS-002

    1 Algorithmhttps://github.com/xufei100/leetcode/tree/mast...

网友评论

      本文标题:leetcode 100

      本文链接:https://www.haomeiwen.com/subject/plvsoqtx.html