Brush the chicken dish Leetcode 101. Symmetric Tree Easy

Leetcode 101. Symmetric Tree Easy

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.

analysis:

Determining whether the mirror tree is a binary tree. First of all, my tree is subject to feel fear, because this topic often involves a recursive cycle, and can not give the idea immediately. But, think about it now, Pasha, because the topics are more routine on the tree, through well-informed, sooner or later one day be "surprising."
First of all, we need to understand what is binary image - as the central point of the break, both sides can overlap, like a mirror. Binary image What characterizes it - the root of the left subtree and right subtree of symmetry, i.e., the left subtree of a node corresponding to the right node left and right subtree, equal to two, and so on.
When writing the program is not difficult to come up with the following methods:

/**
 * 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 == nullptr)
            return true;
        return isSymmetricCore(root->left, root->right);
    }
    bool isSymmetricCore(TreeNode* leftRoot, TreeNode* rightRoot) {
        if (leftRoot == nullptr && rightRoot == nullptr)
             return true;
        else if (leftRoot == nullptr || rightRoot == nullptr)
             return false;
        if (leftRoot->val == rightRoot->val)
             return isSymmetricCore(leftRoot->left, rightRoot->right) && isSymmetricCore(leftRoot->right, rightRoot->left);
        return false;            
    }
};

 

Guess you like

Origin www.cnblogs.com/Flash-ylf/p/11095626.html