Leetcode 对称二叉树
Posted amazing!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 对称二叉树相关的知识,希望对你有一定的参考价值。
Leetcode 101
数据结构定义:
/**
* 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 checkSymmetric(root.left,root.right);
}
public boolean checkSymmetric(TreeNode left,TreeNode right){
if(left == null && right == null){
return true;
}
if(left ==null || right == null){
return false;
}
return left.val == right.val &&
checkSymmetric(left.left,right.right) &&
checkSymmetric(left.right,right.left);
}
}
队列:
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
queue.offer(root);
while(!queue.isEmpty()){
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if(left == null && right == null){
continue;
}
if(left ==null || right == null || left.val != right.val){
return false;
}
queue.offer(left.left);
queue.offer(right.right);
queue.offer(left.right);
queue.offer(right.left);
}
return true;
}
}
以上是关于Leetcode 对称二叉树的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 101.对称二叉树 - JavaScript
⭐算法入门⭐《二叉树》简单03 —— LeetCode 101. 对称二叉树