[leetcode]101. Symmetric Tree

Description

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.

分析

题目的意思是:判断二叉树是否是对称的。

  • 二叉树基本是递归,不仅要判断对称点的值是否相等,也要判断一个节点存在,对称节点不存在的情况。递归的终止条件为两个节点都为空。

代码

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

参考文献

[编程题]symmetric-tree

上一篇:Symmetric Order


下一篇:Symmetric Eigenvalue Decomposition