Same Tree

来源:互联网 发布:多人排班软件 编辑:程序博客网 时间:2024/04/30 00:28
题目描述: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.


1 自己的代码

class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }}public class SameTree {public boolean isSameTree(TreeNode p, TreeNode q) {boolean isSame = false;if(p == null && q== null) return true;else if((p == null && q != null) || (p != null && q == null)) return false;else{//都不为空if(p.val == q.val){if(isSameTree(p.left, q.left)){if(isSameTree(p.right, q.right))isSame = true;}}}        return isSame;    }}
0 0