本文主要是介绍Crack LeetCode 之 101. Symmetric Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原题链接:https://leetcode.com/problems/symmetric-tree/
本题有递归和遍历两种做法,对于遍历,其实是广度优先遍历。以下分别给出了c++和python版本的实现。其实思路一旦清楚了,代码并不复杂。
class Solution {
public:bool isSymmetric(TreeNode* root) {if (root == NULL)return true;return helper( root->left, root->right );}bool helper(TreeNode* l, TreeNode* r) {if (l == NULL && r == NULL)return true;if (l == NULL && r != NULL)return false;if (l != NULL && r == NULL)return false;if (l->val != r->val)return false;return helper(l->right, r->left) && helper(l->left, r->right);}
};
class Solution:def isSymmetric(self, root):if root == None:return Truereturn self.helper(root.left, root.right)def helper(self, left, right):if left == None and right == None:return Trueif left == None and right != None:return Falseif left != None and right == None:return Falseif left.val != right.val:return Falsereturn self.helper(left.right, right.left) and self.helper(left.left, right.right)
class Solution:def isSymmetric(self, root):if root == None:return TrueleftList = root.left;rightList = root.right;while len(leftList)!=0 and len(rightList)!=0:leftListTemp = []rightListTemp = []leftVals = []rightVals = []for item in leftList:if item != None:leftVals.append(item.val)leftListTemp.append(item.left)leftListTemp.append(item.right)else:leftVals.append(None)leftListTemp.append(None)leftListTemp.append(None)for item in rightList:if item != None:rightVals.append(item.val)rightListTemp.append(item.right)rightListTemp.append(item.left)else:rightVals.append(None)rightListTemp.append(None)rightListTemp.append(None)if leftVals != rightVals:return Falseif rightListTemp == leftListTemp:return TrueleftList = leftListTemprightList = rightListTempif len(leftList)==0 and len(rightList)==0:return Truereturn False
这篇关于Crack LeetCode 之 101. Symmetric Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!