leetcode 101. Symmetric Tree
Posted StrongYaYa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 101. Symmetric Tree相关的知识,希望对你有一定的参考价值。
//递归的解法
/** * 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; TreeNode *pleft = root->left; TreeNode *pright = root->right; return isequal(pleft,pright); } bool isequal(TreeNode *pleft, TreeNode *pright){ if(pleft == NULL && pright == NULL ) return true; if(pleft == NULL && pright != NULL) return false; if(pleft != NULL && pright == NULL) return false; if(pleft->val == pright->val) return isequal(pleft->left,pright->right) && isequal(pleft->right,pright->left); else{ return false; } } };
//循环的方法 很悲哀 不太会用C++ STL模板中的stack 和pair 所以用了python
# 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 root is None: return True stack = [[root.left,root.right]] while len(stack) > 0: pair = stack.pop() pleft = pair[0] pright = pair[1] if pleft is None and pright is None: continue if pleft is None or pright is None: return False if pleft.val == pright.val: stack.append([pleft.left,pright.right]) stack.append([pleft.right,pright.left]) else: return False return True
以上是关于leetcode 101. Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]题解(python):101 Symmetric tree