zoukankan      html  css  js  c++  java
  • LeetCode: Symmetric Tree

    Title:

    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
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following is not:

        1
       / 
      2   2
          
       3    3

    /**
     * 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 == NULL)
                return true;
            return fun(root->left,root->right);
            
        }
        bool fun(TreeNode* p1, TreeNode* p2){
            if (!p1 && !p2 )
                return true;
            if (!p1 || !p2 )
                return false;
            return (p1->val == p2->val) && fun(p1->left,p2->right) && fun(p1->right,p2->left);
            
        }
    };
    /**
     * 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 == NULL)
                return true;
            stack<TreeNode* > s;
            s.push(root->left);
            s.push(root->right);
            while (!s.empty()){
                TreeNode* p1 = s.top();
                s.pop();
                TreeNode* p2 = s.top();
                s.pop();
                if (!p1 && !p2)
                    continue;
                if (!p1 || !p2)
                    return false;
                if (p1->val != p2->val)
                    return false;
                s.push(p1->left);
                s.push(p2->right);
                s.push(p1->right);
                s.push(p2->left);
            }
            return true;
        }
        
    };
  • 相关阅读:
    dedeCMS自定义dede标签
    phpstrom配置Xdebug
    ElasticSearch安装 --- windows版
    MySQL语句优化
    PHP高并发商城秒杀
    【java_需阅读】Java中static关键字用法总结
    【java】public,private和protected
    PICT测试工具的安装及使用
    【android】Android am命令使用
    【python】获取指定网页上的所有超级链接
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4497291.html
Copyright © 2011-2022 走看看