首页 > 其他 > 详细

Leetcode 100: Same Tree

时间:2015-11-02 06:41:56      阅读:198      评论: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.

Subscribe to see which companies asked this question

 

题目解析:

判断两个树是否为相同的二叉树。一般二叉树类型的题都有两种解法,recursive的和non-iterative的。

 

非迭代方法:

如果是非迭代的方式,基本上就是用一个LinkedList或Queue或者Stack的数据结构作为中间件来存储树中的点,然后使用一个while循环来判断这个数据结构是否为空,如果为空就退出循环。

 

对于这道题来说,需要有两个Stack分别存储的是两个树的不同节点,然后判断节点的不同情况:

1. p节点为空,q节点不为空      return false

2. p节点不为空,q节点为空      return false

3. p、q节点都不为空但是值不相等   return false

4. p、q节点都不为空,值相等     return true

 

 1 public boolean isSameTree(TreeNode p, TreeNode q) {
 2         LinkedList<TreeNode> l1 = new LinkedList<TreeNode>(),
 3                              l2 = new LinkedList<TreeNode>();
 4         l1.add(p);
 5         l2.add(q);
 6         
 7         while(!l1.isEmpty() && !l2.isEmpty()){
 8             TreeNode c1 = l1.poll();
 9             TreeNode c2 = l2.poll();
10             
11             if(c1 == null){
12                 if(c2 == null)  continue;
13                 else    return false;
14             }
15             if(c2 == null || c1.val != c2.val)  return false;
16             l1.add(c1.left);
17             l1.add(c1.right);
18             
19             l2.add(c2.left);
20             l2.add(c2.right);
21         }
22         return true;
23         
24     }

 

迭代方法:

1 public boolean isSameTree(TreeNode p, TreeNode q) {
2         if(p == null && q == null)  return true;
3         if(p == null || q == null)  return false;
4         
5         return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6         
7     }

 

Leetcode 100: Same Tree

原文:http://www.cnblogs.com/sherry900105/p/4929142.html

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