美文网首页
二叉树相同判断

二叉树相同判断

作者: lintong | 来源:发表于2015-02-28 12:56 被阅读10次

To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.

Algorithm:

sameTree(tree1, tree2)
1: If both trees are empty then return 1.
2: Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively i.e., call sameTree(
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively i.e., call sameTree(
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3: Else return 0 (one is empty and other is not)

/* Given two trees, return true if they are
 structurally identical */
int identicalTrees(struct node* a, struct node* b)
{
    /*1. both empty */
    if (a==NULL && b==NULL)
        return 1;
    /* 2. both non-empty -> compare them */
    if (a!=NULL && b!=NULL)
    {
        return
        (
            a->data == b->data &&
            identicalTrees(a->left, b->left) &&
            identicalTrees(a->right, b->right)
        );
    }
    /* 3. one empty, one not -> false */
    return 0;
}

相关文章

  • 100. Same Tree

    题目 给定两个二叉树,p, q,编写函数判断两个二叉树是否相同。相同的二叉树树形相同且每个节点值也相同。 解析 将...

  • LeetCode 100.相同的树 python/scala

    Same Tree 环境:python 3.6,scala 2.11.8 题意 判断两颗二叉树是否相同(结构相同 ...

  • 求树的深度&判断两棵树是否相同

    求二叉树的深度(递归) 判断两棵树是否相同

  • LeetCode - 0100 - Same Tree

    题目概述 判断两个二叉树是否相同。 原题链接 Same Tree 解题思路 递归的思想:两个二叉树相同就是根节点相...

  • 【算法】-二叉树的问题整理

    持续更新中…… 判断类型的题目: 1.判断两棵二叉树是否相同 [LeetCode OJ]- Same Tree 关...

  • 判断两个二叉树是否相等

    给出两个二叉树,请写出一个判断两个二叉树是否相等的函数。 判断两个二叉树相等的条件是:两个二叉树的结构相同,并且相...

  • 二叉树相同判断

    To identify if two trees are identical, we need to traver...

  • 关于二叉树的算法题

    前序遍历中序遍历后序遍历判断是否是平衡二叉树判断是否是对称二叉树判断二叉树高度按照层遍历二叉树判断二叉树宽度

  • 算法6 Same Tree

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

  • 26.对称二叉树

    判断一个二叉树是否为对称二叉树。对称二叉树的定义是:一个树的镜像和本身相同。 分析:对二叉树进行前序遍历,和一种特...

网友评论

      本文标题:二叉树相同判断

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