剑指offer(61):对称的二叉树
来源:互联网 发布:软件开发是什么工作 编辑:程序博客网 时间:2024/05/26 19:14
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
分析
考虑将二叉树复制一份,如果二叉树是对称的,那么对于同一位置上的节点(记为root1和root2),必须同时满足这些条件:
- root1和root2的value值相等
- root1的left节点等于root2的right节点
- root1的right节点等于root2的left节点
牛客AC:
/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { /** * 请实现一个函数,用来判断一颗二叉树是不是对称的。 * 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 * @param pRoot * @return */ boolean isSymmetrical(TreeNode pRoot) { return isSymmetrical(pRoot, pRoot); } boolean isSymmetrical(TreeNode pRoot1, TreeNode pRoot2) { if(pRoot1 == null && pRoot2 == null) // 同时为空,true return true; if(pRoot1 == null || pRoot2 == null) // 只有一个为空,false return false; if(pRoot1.val != pRoot2.val) // 节点的值不相等,false return false; // 左节点等于右节点,右节点等于左节点 return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left); }}
参考
1. 何海涛,剑指offer名企面试官精讲典型编程题(纪念版),电子工业出版社
0 0
- 剑指offer(61):对称的二叉树
- 剑指offer--对称的二叉树
- 剑指offer 59 - 对称的二叉树
- 《剑指offer》对称的二叉树
- 剑指offer-对称的二叉树
- 剑指offer—对称的二叉树
- 剑指offer:对称的二叉树
- 剑指offer:对称的二叉树
- [剑指offer]对称的二叉树
- 剑指Offer--059-对称的二叉树
- 《剑指offer》:[59]对称的二叉树
- 剑指offer-对称的二叉树
- 剑指offer---对称的二叉树
- 剑指offer 对称的二叉树
- 【剑指Offer】对称的二叉树
- 剑指offer 对称的二叉树
- 剑指offer-对称的二叉树
- 剑指offer-58.对称的二叉树
- hdu ztr loves lucky numbers (最小的但不小于n的幸运数字是多少,幸运数字只含4和7,且4的个数等于7的个数)
- Leetcode:62. Unique Paths
- android 5.x—Palette图片取色调
- 4.图像标记<img>
- hdu 5675 ztr loves math【思维】
- 剑指offer(61):对称的二叉树
- TeamTalk---服务端架构
- 【HDU2089】不要62【数位DP】【记忆化搜索】
- 工厂方法模式
- android UI(1)-PopupWindow
- 74、JDK安装与环境变量配置
- leetcode-110. Balanced Binary Tree
- C语言
- 已更改或删除的行值要么不能使该行成为唯一行,要么改变了多个行