本文主要是介绍[LeetCode]101. Symmetric Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意: 给你一棵二叉树,判断是否是镜面对称
思路: 从根节点开始,依次向两边展开,左右分别相等之后,分别判断左节点和右节点的(左孩子和右孩子)和(右孩子和左孩子)【镜面对称】,发现不相等或者为空,则返回错误
代码:
public boolean isSymmetric(TreeNode root) {if(root == null){return true;}return compare(root.left, root.right);}public boolean compare(TreeNode left, TreeNode right){if((left == null && right != null)||(left != null && right == null)){return false;}if(left == null && right == null){return true;}if(left.val != right.val){return false;}boolean left_ = compare(left.left, right.right);boolean right_ = compare(left.right, right.left);return left_ && right_;}
这篇关于[LeetCode]101. Symmetric Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!