[递归]LeetCode101. Symmetric Tree

[递归]LeetCode101. Symmetric Tree_第1张图片

递归判断树是否是对称的,不难,但是要注意root为NULL和某一个结点为NULL的情况

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

你可能感兴趣的:([递归]LeetCode101. Symmetric Tree)