(二叉树 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;
    }
};

猜你喜欢

转载自www.cnblogs.com/Weixu-Liu/p/10738607.html