首页 > 其他 > 详细

Same Tree

时间:2015-01-13 14:13:53      阅读:232      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/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.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null)
          return true;
        if(p != null && q != null && p.val == q.val){
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }else{
          return false;
     } } }

解题思路:

递归。两个树相等,当且仅当当前节点value相等,并且左右两个子树也都相等。

退出条件:

当前节点为空。

注意点:

搞清楚当前阶段null和left或right为null的区别。

Same Tree

原文:http://www.cnblogs.com/NickyYe/p/4221030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!