• 判断对称二叉树


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

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

    解题思路:

    若二叉树是镜像对称的,处于同一层对称的两个节点node1与node2,

    node1的值与node2的值必相等,且node1.left与node2.right的值也相等,且node1.right 与 node2.left的值也相等。

    如上例1中,同处于第二层的对称的两个节点(2  与  2),二者值相等,且node1的左子结点(3)与node2的右子节点(3)值相等,且node1的右子结点(4)与node2的左子节点(4)值相等。

    实现代码:

        // 记录判断结果
        private static boolean res = true;
    
        private static void test(TreeNode node1, TreeNode node2) {
    
            // 若已得到该树不对称,返回
            if (!res) return;
    
            if (node1!=null && node2!=null) {
                // 两个节点的值是否相等
                if (node1.val != node2.val) {
                    res = false;
                    return;
                }
                // 两个节点的子节点
                test(node1.left, node2.right);
                test(node1.right, node2.left);
            }
            else if (node1==null && node2==null) return;
            else res = false;
        }
  • 相关阅读:
    Python2 cmp() 函数
    Python round() 函数
    Python floor() 函数
    Python ceil() 函数
    Python abs() 函数
    Python oct() 函数
    Python ord() 函数
    Python hex() 函数
    Python2 unichr() 函数
    Android--------工具类StatusBarUtil实现完美状态栏
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/9286009.html
Copyright © 2020-2023  润新知