[Leetcode101]對稱二叉樹
阿新 • • 發佈:2018-11-30
給定一個二叉樹,檢查它是否是映象對稱的。
二話不說上來就是遞迴騷操作。
python:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root : return self.isEqual(root.left,root.right) return True def isEqual(self,l,r): if l != None and r != None: if l.val != r.val: return False else: return self.isEqual(l.left,r.right) & self.isEqual(l.right,r.left) if l == None and r == None: return True 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) return isEqual(root->left,root->right); else return true; } bool isEqual(TreeNode* l, TreeNode* r){ if(l != NULL && r != NULL){ if(l->val != r->val) return false; else return isEqual(l->right,r->left) & isEqual(l->left,r->right); } if(l == NULL && r == NULL) return true; else return false; } };