当前位置:  首页>> 技术小册>> 数据结构与算法(下)

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

解法

比较二叉树的前序遍历序列和对称前序遍历序列是否一样,若是,说明是对称的。

  1. /**
  2. * @author bingo
  3. * @since 2018/11/22
  4. */
  5. /*
  6. public class TreeNode {
  7. int val = 0;
  8. TreeNode left = null;
  9. TreeNode right = null;
  10. public TreeNode(int val) {
  11. this.val = val;
  12. }
  13. }
  14. */
  15. public class Solution {
  16. /**
  17. * 判断是否是对称二叉树
  18. * @param pRoot 二叉树的根结点
  19. * @return 是否为对称二叉树
  20. */
  21. boolean isSymmetrical(TreeNode pRoot) {
  22. return isSymmetrical(pRoot, pRoot);
  23. }
  24. private boolean isSymmetrical(TreeNode pRoot1, TreeNode pRoot2) {
  25. if (pRoot1 == null && pRoot2 == null) {
  26. return true;
  27. }
  28. if (pRoot1 == null || pRoot2 == null) {
  29. return false;
  30. }
  31. if (pRoot1.val != pRoot2.val) {
  32. return false;
  33. }
  34. return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left);
  35. }
  36. }

测试用例

  1. 功能测试(对称的二叉树;因结构而不对称的二叉树;结构对称但节点的值不对称的二叉树);
  2. 特殊输入测试(二叉树的根结点为空指针;只有一个节点的二叉树;所有节点的值都相同的二叉树)。

该分类下的相关小册推荐: