[leetcode]101.Symmetric Tree
发布时间:2020-12-14 04:21:12 所属栏目:大数据 来源:网络整理
导读:题目 Given a binary tree,check whether it is a mirror of itself (ie,symmetric around its center). For example,this binary tree [1,2,3,4,3] is symmetric 解法一 思路 上来直接采用Same Tree的第二种解法,思路一模一样。 代码 /** * Definition for
题目Given a binary tree,check whether it is a mirror of itself (ie,symmetric around its center). For example,this binary tree [1,2,3,4,3] is symmetric 解法一思路上来直接采用Same 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) {
if(root == null) return true;
Deque<TreeNode> queue = new LinkedList<>();
queue.addLast(root.left);
queue.addLast(root.right);
while(!queue.isEmpty()){
TreeNode l = queue.removeFirst();
TreeNode r = queue.removeFirst();
if(l == null && r == null) continue;
else if(l == null || r == null || l.val != r.val)
return false;
else {
queue.addLast(l.left);
queue.addLast(r.right);
queue.addLast(l.right);
queue.addLast(r.left);
}
}
return true;
}
}
解法二思路递归的方法,一开始没有想出来,看了别人的解答发现构造一个辅助函数就容易理解很多。直接看代码就能理解思路。 代码/**
* 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 isMirror(root.left,root.right);
}
public boolean isMirror(TreeNode p,TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null || q.val != p.val)
return false;
return isMirror(p.left,q.right) && isMirror(p.right,q.left);
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
