zoukankan      html  css  js  c++  java
  • (二叉树 DFS 递归) 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 [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.

    --------------------------------------------------------------------------------------------------------------------------

    symmetric是对称的,此题用DFS会比较简单的,关键是要找出合适的递归方法。

    C++代码:

    官方题解:https://leetcode.com/problems/symmetric-tree/solution/

    /**
     * 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) {
            return Recur(root,root);
        }
        bool Recur(TreeNode* l,TreeNode* r){
            if(l==NULL && r==NULL) return true;
            if(l==NULL || r==NULL) return false;
            return (l->val == r->val) && Recur(l->left,r->right) && Recur(l->right,r->left);
        }
    };

    也可以用迭代,可以用BFS

    C++代码:

    /**
     * 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) {
            queue<TreeNode*> q;
            if(!root) return true;
            q.push(root);
            q.push(root);
            while(!q.empty()){
                auto t1 = q.front();
                q.pop();
                auto t2 = q.front();
                q.pop();
                if(!t1 && !t2) continue;
                if(!t1 || !t2) return false;
                if(t1->val != t2->val) return false;
                q.push(t1->left);
                q.push(t2->right);
                q.push(t1->right);
                q.push(t2->left);
            }
            return true;
        }
    };
  • 相关阅读:
    下面我使用vector容器为基础来构成一棵树
    COM编程
    vc买书指导
    [转帖] 职场学习=贼学技术
    创业者应具备的基本商业知识
    比尔盖茨的10大优秀员工准则(看你符合几条)
    损害个人魅力的26条错(转帖)
    流行:时尚健康美女10大标准
    人生要做的30件事(转帖)
    最伟大的管理原则
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10738607.html
Copyright © 2011-2022 走看看