leetcode| Same Tree

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.

题目:给定两个二叉树,判断他们是不是相等,相等的定义是结构以及各个节点的值都相同

思路:不得不说,二叉树在leetcode上几乎都可以用递归求解,这个是有它的机构觉得,如我之前博文里的求二叉树的深度,反转二叉树,这道题也不例外,注意情况的判断处理,递归求解的代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public boolean isSameTree(TreeNode p, TreeNode q) {

  if(p == null && q !=null) return false;

  if(q == null && p!=null) return false;

  if(q == null && q == null) return true;

  if(p.val == q.val) {

    return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);

  }else{

    return false;

  }

}

 

posted @ 2016-07-20 10:16  Roger's  阅读(148)  评论(0编辑  收藏  举报