LeetCode-100. Same Tree

来源:互联网 发布:怪兽使者与少年知乎 编辑:程序博客网 时间:2024/06/05 00:39

题目描述

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.

解题思路

利用递归的方式求解,判断p和q是不是同一棵树,即判断以下三个条件是否满足,如果满足,则为同一棵树;如果不满足,则不是:

  1. 节点p的当前值是否等于q的当前值
  2. p的左子树和q的左子树是不是同一棵树
  3. p的右子树和q的右子树是不是同一棵树

代码

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public boolean isSameTree(TreeNode p, TreeNode q) {        if((p == null && q != null) || (p != null && q == null))           return false;        if(p == null && q == null)            return true;        return p.val == q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);    }}
原创粉丝点击