• Leetcode之101. Symmetric Tree Easy


    Leetcode 101. Symmetric Tree Easy

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following [1,2,2,null,3,null,3] is not:

        1
       / 
      2   2
          
       3    3
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    分析:

    判断一棵树是否是镜像二叉树。首先,我对树的题目是心存畏惧的,因为这种题目往往涉及递归、循环,而且无法立刻给出思路。但是,现在想想,怕啥,因为关于树的题目套路比较多,通过见多识广,早晚有一天会“见怪不怪”。
    首先,我们要明白什么是镜像二叉树——以中央作为对折点,左右两边可以重合,就像镜子一样。镜像二叉树有什么特点呢——根结点的左子树和右子树对称,即左子树的左节点对应着右子树的右节点,二者要相等,以此类推。
    在写程序的时候就不难想出以下方法:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (root == nullptr)
                return true;
            return isSymmetricCore(root->left, root->right);
        }
        bool isSymmetricCore(TreeNode* leftRoot, TreeNode* rightRoot) {
            if (leftRoot == nullptr && rightRoot == nullptr)
                 return true;
            else if (leftRoot == nullptr || rightRoot == nullptr)
                 return false;
            if (leftRoot->val == rightRoot->val)
                 return isSymmetricCore(leftRoot->left, rightRoot->right) && isSymmetricCore(leftRoot->right, rightRoot->left);
            return false;            
        }
    };
  • 相关阅读:
    使用NDK开发SQLite3
    SQL Server 2005 Default Trace (默认跟踪)
    MySQL 获得当前日期时间 函数
    利用UltraISO写入U盘安装系统,条件:电脑支持USBHDD ,U盘容量足够
    Sicily 1157 The hardest problem
    Histogram of oriented gradients(HOG)
    IE中的CSS3不完全兼容方案
    MySQL如何查询两个日期之间的记录
    查找某个字段最大值的记录 SQL 语句
    用 jQuery 实现页面滚动(Scroll)效果的完美方法
  • 原文地址:https://www.cnblogs.com/Flash-ylf/p/11095626.html
Copyright © 2020-2023  润新知