首页 > 代码库 > [leetcode] 22.Same Tree

[leetcode] 22.Same Tree

同是递归简单题

?
1
2
3
4
5
6
7
8
9
10
11
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        boolean flag = true;
        if(p == null && q == null)
            return true;
        else if(p != null && q != null && p.val == q.val)
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        else
            return false;
    }
}

若不用递归: 来自: http://www.cnblogs.com/lautsie/p/3247097.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        LinkedList<TreeNode> left = new LinkedList<TreeNode>();
        LinkedList<TreeNode> right = new LinkedList<TreeNode>();
 
        left.offer(p);
        right.offer(q);
 
        while (left.size() != 0 && right.size() != 0) {
            TreeNode ln = left.poll();
            TreeNode rn = right.poll();
            if (ln == null && rn == null) continue;
            if (ln == null || rn == null) return false;
            if (ln.val != rn.val) return false;
             
            left.offer(ln.left); left.offer(ln.right);
            right.offer(rn.left); right.offer(rn.right);
        }
        if (left.size() != 0 || right.size() != 0) return false;
        return true;
    }
}

  

基础:

此处的LinkedList继承自Queue

LinkedList是List接口的实现类,也是Deque接口的实现类,Deque接口是Queue的子接口。兼具双向队列,栈和List集合的用法

1)LinkedList作为List使用时,一般采用add / get方法来 压入/获取对象
2)LinkedList作为Queue使用时,才会采用 offer/poll 等方法,没有empty(),这些方法是用于支持队列应用的。 与一般队队一样,offer插入元素到队尾,poll访问并删除队首元素。另有pollLast可以访问并删除队尾元素。
3)LinkedList作为栈使用时,会用到 push/pop方法, 注意,栈的操作是在队首方向进行的。即push会插到队首,pop会访问并删除队首元素。

访问不删除对象还可用getFirst()/getLast()  peekFirst()/peekLast()