101. Symmetric Tree
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.
题意:
给定一个二叉树,检查它是否是自身的镜像(即围绕其中心轴对称)。
思路:
方法一:
递归实现,思路比较简练,只要注意控制好递归结束的条件:
1.停止条件是 left\==NULL && right==NULL return true;
2.停止条件是 left!=NULL || right != NULL return false;
3.left->val == right->val 比较left->left和right.right && left->right和right->left;
4.任何条件不成立都是false;
1 | class Solution { |
方法二:
非递归两个队列实现,层序遍历的左右队列中左右子树进行相互比较,两个队列,分别存储每一层根节点的下一层的左右子树,右左子树:
1 | class Solution { |
方法三:
非递栈实现,用一个栈来实现,要注意进栈时的左右子树节点进栈的顺序。
1 | class Solution { |