首页 > 其他 > 详细

Same Tree

时间:2015-11-02 12:04:26      阅读:156      评论:0      收藏:0      [点我收藏+]

题目:

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 Solution
 2 {
 3 public:
 4     bool isSameTree(TreeNode *p, TreeNode *q)
 5     {
 6         if (!p && !q) return true; // 终止条件
 7         if (!p || !q) return false; 
 8         return p->val == q->val // 三方合并
 9                && isSameTree(p->left, q->left)
10                && isSameTree(p->right, q->right);
11     }
12 };

这题开始写错了,主要是没考虑第二种情况

第一种,节点都为nullptr,两树相等,主要用于叶子节点的判断

第二种,一个节点存在val,一个节点为nullptr,这样的话在语法上用p->val == q ->val 是错的,因为节点为nullptr的没有val

第三种,val存在且相等,分别判断两个树的左右子树是否相等

Same Tree

原文:http://www.cnblogs.com/raichen/p/4929624.html

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