101. Symmetric Tree(图解)

    科技2022-08-14  92

    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

    Follow up: Solve it both recursively and iteratively.

    Solution

    C++

    Sol1:

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

    Sol2:

    /** * 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; queue<TreeNode*> q; q.push(root->left); q.push(root->right); while(!q.empty()) { TreeNode* x1 = q.front(); q.pop(); TreeNode* x2 = q.front(); q.pop(); if(x1 == NULL && x2 == NULL) continue; if(x1 == NULL || x2 == NULL) return false; if(x1->val != x2->val) return false; q.push(x1->left); q.push(x2->right); q.push(x1->right); q.push(x2->left); } return true; } };

    Explanation

    Sol1: Recursive:

    Sol2: Iterative:

    Processed: 0.016, SQL: 8