Same Tree

来源:互联网 发布:mybatis sql注入 编辑:程序博客网 时间:2024/06/06 11:48
题目:

Given two binary trees, write a function to check if they are equal or not.

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

判断两棵二叉树是否相等,相等的定义是树的结构一样且每个节点值相等

起先想着写个先序遍历然后把按先序把节点的值存到集合里,再将两个集合进行比对,结果行不通

因为树的结构不同输出的先序序列也可能是一样的 比方{10, 5, 15} 和 {10, 5, #, #, 15},这里用顺序存储表示树

public boolean isSameTree(TreeNode p, TreeNode q) {boolean result = false;if (p == null && q == null) {        return true;        }        if (p != null && q != null) {        result = p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) ? true : false;        }        return result;    }


树不相等的情况有很多,所以反过来想容易点,树相等的情况只有两棵树都是null或者当前节点值相等且左右子树均相等,其他都是false


0 0
原创粉丝点击