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;
        }
    };
  • 相关阅读:
    mysql的多表查询join
    JMeter源码集成到Eclipse
    jmeter关联 正则表达式提取器
    JMeter结果树响应数据中文乱码解决办法
    BZOJ 2080: [Poi2010]Railway 双栈排序
    BZOJ 4384: [POI2015]Trzy wieże
    BZOJ 4325: NOIP2015 斗地主
    BZOJ 1142: [POI2009]Tab
    第10章 内核同步方法
    第1章 Linux内核简介
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10738607.html
Copyright © 2011-2022 走看看