博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
101. Symmetric Tree
阅读量:4599 次
发布时间:2019-06-09

本文共 2012 字,大约阅读时间需要 6 分钟。

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

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

 

Note:

Bonus points if you could solve it both recursively and iteratively.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Pair{    TreeNode x;    TreeNode y;    public Pair(TreeNode x, TreeNode y){        this.x = x;        this.y = y;    }}public class Solution {    // recursive    // public boolean isSymmetric(TreeNode root) {    //     if(root == null)    //         return true;            //     return Symmetric(root.left, root.right);    // }    // public boolean Symmetric(TreeNode left, TreeNode right){    //     if(left == null || right == null){    //         return left == right;    //     }    //     if(left.val != right.val){    //         return false;    //     }    //     return Symmetric(left.left, right.right) &&  Symmetric(left.right, right.left);    // }        public boolean isSymmetric(TreeNode root) {        if(root == null || root.left == null && root.right == null)            return true;        Queue
queue = new LinkedList
(); queue.offer(new Pair(root.left, root.right)); while(!queue.isEmpty()){ Pair values= queue.poll(); if(values.x == null && values.y == null) continue; if(values.x == null || values.y == null || values.x.val != values.y.val) return false; if(values.x != null && values.y != null){ queue.offer(new Pair(values.x.left, values.y.right)); queue.offer(new Pair(values.x.right, values.y.left)); } } return true; }}

 

转载于:https://www.cnblogs.com/joannacode/p/5998968.html

你可能感兴趣的文章
线段树 (区间查询最大 区间求和 区间加)带lazy
查看>>
三十而立,从零开始学ios开发(十二):Table Views(上)
查看>>
MySQL中的decimal
查看>>
gitlab+jenkins持续集成(一)
查看>>
4.signed/unsigned char
查看>>
iOS,UIImage有个contentmodel属性
查看>>
Debian 7 amd64 + fbterm + ucimf
查看>>
数据结构之【排序】复习题
查看>>
spring boot 首次请求Controller慢
查看>>
事件绑定
查看>>
grep命令详解
查看>>
iterm2快捷键
查看>>
asp.net 生成PDF方法
查看>>
EntityFramework 7 Join Count LongCount 奇怪问题(已修复)
查看>>
设计模式---组件协作模式之模板方法模式(Tempalte Method)
查看>>
程序员心理看WEB开发框架
查看>>
@Data 注解在实体类的使用可省去生成GET,SET方法
查看>>
webpack 介绍 & 安装 & 常用命令
查看>>
ASP.NET刷新页面的六种方法总结
查看>>
ECSHOP增加独立评论页面,并分页显示
查看>>