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.
思路:同时递归两棵树,如果节点值不相等或者一棵树已经递归到头了而另一棵还没有,返回false;
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 class Solution {11 public boolean isSameTree(TreeNode p, TreeNode q) {12 if (p==null&&q==null)13 return true; //一开始如果传进两颗空树,返回true14 if ((p==null&&q!=null)||(p!=null&&q==null))15 return false; //递归过程中,一棵树递归到头了,而另一颗没有16 if (p.val!=q.val)17 return false;18 return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); 19 // 同时递归20 }21 }