Leetcode P0101"Symmetric Tree" 题解

2020/09/03 Leetcode

博文中会简要介绍Leetcode P0101题目分析及解题思路。

“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

以下是Java的题解代码实现。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        
        return this.validate(root.left, root.right);
    }
    
    private boolean validate(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 this.validate(left.left, right.right) && this.validate(left.right, right.left);
    }
}

以下是C++的题解代码实现。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL)
            return true;
        
        return this->Validate(root->left, root->right);
    }
    
private:
    bool Validate(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 this->Validate(left->left, right->right) && this->Validate(left->right, right->left);
    }
};

Search

    Table of Contents