Leetcode - Tree - Symmetric Tree
2014-04-29 16:05
405 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
/** * Definition for binary tree * 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 isEqual(root->left,root->right); } bool isEqual(TreeNode *l, TreeNode *r) { if(l==NULL&&r==NULL) return true; if(l==NULL&&r!=NULL||l!=NULL&&r==NULL) return false; if(l->val==r->val&&isEqual(l->left,r->right)&&isEqual(l->right,r->left)) return true; else return false; } };
/** * Definition for binary tree * 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; stack<TreeNode*> nodeStack; nodeStack.push(root->left); nodeStack.push(root->right); TreeNode *lhs=NULL,*rhs=NULL; while(nodeStack.size()>1) { lhs=nodeStack.top(); nodeStack.pop(); rhs=nodeStack.top(); nodeStack.pop(); if(!lhs&&!rhs) continue; if((lhs&&!rhs)||(!lhs&&rhs)) return false; if(lhs->val!=rhs->val)return false; nodeStack.push(lhs->left); nodeStack.push(rhs->right); nodeStack.push(lhs->right); nodeStack.push(rhs->left); } return true; } };
相关文章推荐
- 【LeetCode从零单排】No100 Same Tree && No101 Symmetric Tree
- LeetCode-Same Tree & Symmetric Tree
- leetcode_101题——Symmetric Tree (树tree,递归,还有迭代没想出来)
- LeetCode[Tree]: Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- [leetcode][tree] Symmetric Tree
- 【Leetcode】Symmetric Tree (Tree Judge)
- [LeetCode 题解]: Binary Tree Preorder Traversal
- 【C++】【LeetCode】98. Validate Binary Search Tree
- LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:Maximum Depth of Binary Tree
- leetcode——104—— Maximum Depth of Binary Tree
- [LeetCode] Binary Tree Level Order Traversal
- LeetCode No.173 Binary Search Tree Iterator
- 【Leetcode】Binary Tree Preorder Traversal
- LeetCode | Recover Binary Search Tree
- Leetcode 199 Binary Tree Right Side View
- LeetCode题解——Symmetric Tree
- [Leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Convert Sorted List to Binary Search Tree