swift 算法 简单19.对称二叉树

知识共享许可协议 Creative Commons

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

解法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */
class Solution {
    func isSymmetric(_ root: TreeNode?) -> Bool {
        return self.isTreeEquel(root , root)
    }
    func isTreeEquel(_ root: TreeNode?,_ root2: TreeNode?) -> Bool {
        if(root == nil && root2 == nil){
            return true;
        }

        if(root != nil && root2 != nil && root?.left?.val == root2!.right?.val && root2?.left?.val == root!.right?.val){
            //递归查看节点和值
            return isTreeEquel(root!.left,root2!.right)  && isTreeEquel(root2!.left,root!.right)
        }else {
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/huanglinxiao/article/details/91946619
今日推荐