LeetCode--Symmetric Tree
2017-11-20 15:12
239 查看
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:
But the following [1,2,2,null,3,null,3] is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
方法一:递归。每次判断对称的两个节点是否相同,以及递归判断他们对称的子节点是否相同。
方法二:非递归。还是用堆栈,基本思路和上面一样,就是注意子节点都是空节点就跳过继续循环。
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. * 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 true; return isSymmetric(root->left,root->right); } bool isSymmetric(TreeNode* p,TreeNode* q){ if(!p&&!q) return true; if(!p||!q) return false; return (p->val==q->val)&&isSymmetric(p->left,q->right)&&isSymmetric(p->right,q->left); } };
方法二:非递归。还是用堆栈,基本思路和上面一样,就是注意子节点都是空节点就跳过继续循环。
/** * 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 true; stack<TreeNode*>s; s.push(root->left); s.push(root->right); while(!s.empty()){ TreeNode *p=s.top(); s.pop(); TreeNode *q=s.top(); s.pop(); if(!p&&!q) continue; if(!p||!q) 4000 return false; if(p->val!=q->val) return false; s.push(p->left); s.push(q->right); s.push(p->right); s.push(q->left); } return true; } };
相关文章推荐
- LeetCode: Symmetric Tree 解题报告
- leetcode:Symmetric Tree
- Symmetric Tree | leetcode 101【Java solution】
- [LeetCode] Symmetric Tree
- 【leetcode】Symmetric Tree
- LeetCode(1) Symmetric Tree
- 【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】
- 【leetcode】Symmetric Tree
- leetcode-101-Symmetric Tree
- [leetcode]Symmetric Tree
- LEETCODE: Symmetric Tree
- 【LeetCode】Symmetric Tree
- [LeetCode][Java] Symmetric Tree
- Symmetric Tree [LeetCode]
- Leetcode-Symmetric Tree
- LeetCode-101-Symmetric Tree(判断是否为对称树)
- LeetCode--No.101--Symmetric Tree
- Leetcode练习- Symmetric Tree
- leetcode:Symmetric Tree
- leetcode101 Symmetric Tree