101. 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

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:


        def dfs(root1,root2):
            if root1 == None and root2 == None:
                return True
            if root1== None and root2 != None:
                return False
            if root1 != None and root2 == None:
                return False
            if root1.val != root2.val:
                return False
            return dfs(root1.left,root2.right) and dfs(root1.right,root2.left)
        
        return dfs(root.left,root.right)

 

 

 

 

 

class Solution {
public:
    bool two_tree_issy(TreeNode* a, TreeNode* b) {
        if (a != nullptr && b != nullptr) {
            return (a->val==b->val) && two_tree_issy(a->left,b->right) && two_tree_issy(a->right,b->left);} else if (a ==nullptr && b == nullptr) {
            return true;
        } else if (a==nullptr || b == nullptr){
            return false;
        }
        return false;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) {
            return true;
        }
        return two_tree_issy(root->left,root->right);
    }
};

 

 1 class Solution {
 2     public boolean isSymmetric(TreeNode root) { 
 3         if(root ==null) return true;
 4         return  isSy(root.left,root.right);
 5     }
 6     public boolean isSy(TreeNode s,TreeNode t) {
 7         if(s == null || t == null) return s==t;
 8         
 9         if(s.val != t.val) return false;
10         
11         return isSy(s.left,t.right) && isSy(s.right,t.left);
12     }
13 }

 

posted @ 2017-10-27 10:10  乐乐章  阅读(139)  评论(0编辑  收藏  举报