【刷题】Leetcode 101. Symmetric Tree

6 篇文章 0 订阅

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

 1
 / \
2   2
/ \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

  1
 / \
2   2
  \   \
   3    3

最近刷的还是老题,想提高下速度,结果每天也是各种事耽误着。恍恍惚惚莺莺燕燕碌碌无为就是了。

这道题想到的是层遍历每一行,再判断是否是回文。当然也可以递归来做。记得以前刷的时候是递归做的,但是现在用它练下BFS。

Runtime: 1 ms, faster than 48.79% of Java online submissions for Symmetric Tree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();       
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            ArrayList<Integer> list = new ArrayList<Integer>();
            for(int i = 0; i < size; i++){
                TreeNode node = q.poll();
                if(node == null)
                    list.add(-1);
                else{
                    list.add(node.val);
                    q.add(node.left);
                    q.add(node.right);
                }
                
            }
            if(!isPalindrome(list))
                return false;
        }
        return true;
    }
    
    public boolean isPalindrome(ArrayList<Integer> list){
        int l = 0;
        int r = list.size() - 1;
        while(l <= r){
            if(list.get(l) != list.get(r))
                return false;
            l++;
            r--;
        }
        return true;
    }
}

总结:

  • 在这句话刚开始出错了,每一层回来得重新定义新的list, 脑子不太好使。ArrayList list = new ArrayList();
  • 为空的情况, list.add(-1);
  • 感觉这种方法挺笨,纯是晚上自己想的。

递归写法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        return helper(root.left, root.right);
    }
    
    public boolean helper(TreeNode left, TreeNode right){
        if(left == null && right == null)
            return true;
        if(left == null || right == null)
            return false;
        if(left.val != right.val)
            return false;
        return helper(left.left, right.right) && helper(left.right, right.left);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值