首页 > 其他 > 详细

【Leetcode】【Easy】Same Tree

时间:2014-11-19 07:15:42      阅读:180      评论: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、只关注单个结点,结点的孩子交给递归去做,这样可以最简化逻辑;

2、结点是否存在、结点值是否相等、结点是否有孩子,是三个不同的概念(“结点是否有孩子”的概念本题中未体现);

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 class Solution {
12 public:
13     bool isSameTree(TreeNode *p, TreeNode *q) {
14         if (!p && !q)
15             return true;
16         
17         if ((p&&!q) || (!p&&q) || (p->val!=q->val))
18             return false;
19             
20         return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
21     }
22 };

 

不用递归的解法:

引用先序/中序/后序/按层等遍历二叉树的思想,用堆栈(数组)存放遍历到的结点,进栈出栈的同时进行比较:

 

附录:

C++中vector、stack、queue用法和区别

递归/非递归遍历二叉树

【Leetcode】【Easy】Same Tree

原文:http://www.cnblogs.com/huxiao-tee/p/4107031.html

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