美文网首页
算法6 Same Tree

算法6 Same Tree

作者: holmes000 | 来源:发表于2017-10-08 16:48 被阅读0次

题目:给出两个二叉树,写一个方法判断这两个树是否相同。
两个二叉树如果结构一致,并且每个节点有相同的值,则我们认为它们相同。

思路:先判断两个二叉树的每个对应位置节点相不相同,主要是用到递归。

代码:

public boolean isSameTree(TreeNode p, TreeNode q) {
    //若搜索到同时为 null 说明搜索完了还是对的,那就是true
    if(p == null && q == null) return true;
    //若一个null,一个不null,明显返回false
    if(p == null || q == null) return false;
    //如果相等继续往下判断
    if(p.val == q.val)
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    return false;
}

相关文章

  • 算法6 Same Tree

    题目:给出两个二叉树,写一个方法判断这两个树是否相同。两个二叉树如果结构一致,并且每个节点有相同的值,则我们认为它...

  • [Leetcode][Tree--2]树相关题目汇总/分析/总结

    Binary Tree Con.(6) Structure of Tree100 Same Tree101 Sym...

  • 100 Same Tree

    title: Same Treetags:- same-tree- No.100- simple- tree- r...

  • Same Tree

    //100 Given two binary trees, write a function to check i...

  • Same Tree

    判断两个二进制树是否相同(树节点总数相同,树结构相同)通过迭代的方式解决:遍历:依次遍历树的节点的左右节点出口:树...

  • Same Tree

    题目描述Given two binary trees, write a function to check if ...

  • LeetCode算法解题集:Same Tree

    题目:Given two binary trees, write a function to check if t...

  • DFS-special

    Validate Binary Search Tree Same Tree (基础) 101.symmetric ...

  • 100 Same Tree

    原题链接:Same Tree

  • 100. Same Tree

    100. Same Tree 题目: https://leetcode.com/problems/same-tre...

网友评论

      本文标题:算法6 Same Tree

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