leetcode 101. 对称二叉树

思路 递归

用一个函数辅助判断左右子树是否完全对称,对根节点进行输入递归判断结果。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.judge_is_sys(root,root)
    def judge_is_sys(self,proot1,proot2):
        if not proot1 and not proot2:
            return True
        if not proot1 or not proot2:
            return False
        if proot1.val == proot2.val:
            return self.judge_is_sys(proot1.left,proot2.right) and self.judge_is_sys(proot1.right,proot2.left)
        else:
            return False

C++代码:

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

 

posted @ 2021-09-26 15:36  A-inspire  Views(25)  Comments(0Edit  收藏  举报