zoukankan      html  css  js  c++  java
  • LeetCode(101)Symmetric Tree

    题目

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

    For example, this binary tree is symmetric:
    1
    But the following is not:
    2
    Note:
    Bonus points if you could solve it both recursively and iteratively.

    confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

    分析

    判断一棵二叉树是否为对称树;

    仍然采用递归的思想,判断该树的左右子树是否对称;

    若二叉树p与二叉树q对称,也就是说其根节点相同,p左子树应与q右子树对称,同理,p右子树应与q左子树对称;

    AC代码

    /**
     * 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)
                return true;
            else
                //判断左右子树是否对称
                return isSymmetricTree(root->left, root->right);
        }
    
        bool isSymmetricTree(TreeNode* p, TreeNode* q) {
            //如果两个二叉树均为空,则返回true
            if (!p && !q)
            {
                return true;
            }
            //如果两者其一为空树,则返回false
            else if (!p || !q)
            {
                return false;
            }
            else{
                if (p->val != q->val)
                    return false;
                else
                    //p左子树应与q右子树对称,同理,p右子树应与q左子树对称
                    return isSymmetricTree(p->left, q->right) && isSymmetricTree(p->right, q->left);
            }
        }
    };
  • 相关阅读:
    iOS设计模式
    Objective-C的可变是如何实现的?
    很好的UI动效设计参考
    MAC OS Finder 中快速定位指定路径
    IOS应用沙盒文件操作
    Java -- 单例模式
    Java眼中的XML--文件读取--2 应用SAX方式解析XML
    Java眼中的XML--文件读取--1 应用DOM方式解析XML
    配置JDK环境变量
    IOS开发之SVN的使用
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214830.html
Copyright © 2011-2022 走看看