leetcode刷题笔记一百零一题 对称二叉树
源地址:101. 对称二叉树
问题描述:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/
2 2
/ /
3 4 4 3但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/
2 2
3 3进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
/**
本题较为简单,可主要分为递归与迭代两种方法
如何判断二叉树镜像?
1.p与q根结点值相等
2.p的左子树与q右子树相同,p的右子树与q的左子树如同
*/
//递归
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
object Solution {
def isSymmetric(root: TreeNode): Boolean = {
def rec(leftTree: TreeNode, rightTree: TreeNode): Boolean = {
if (leftTree == null && rightTree == null) return true
if (leftTree == null || rightTree == null) return false
if (leftTree.value == rightTree.value) return(rec(leftTree.left, rightTree.right) && rec(leftTree.right, rightTree.left))
return false
}
return rec(root, root)
}
}
//迭代,这种情况需要使用队列
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
import scala.collection.mutable.Queue
import util.control.Breaks._
object Solution {
def isSymmetric(root: TreeNode): Boolean = {
val queue = new Queue[TreeNode]()
queue.enqueue(root)
queue.enqueue(root)
while (queue.isEmpty == false){
breakable{
val left = queue.dequeue
val right = queue.dequeue
if (left == null && right == null) break()
if (left == null || right == null) return false
if (left.value != right.value) return false
queue.enqueue(left.left)
queue.enqueue(right.right)
queue.enqueue(left.right)
queue.enqueue(right.left)
}
}
return true
}