题目
思路
重点是理解整个的递归思路。
二叉树的题目的关键就在于递归。
以本题为例,判断二叉树是否镜像相等,自顶而下递归考虑。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean mirrorTree(TreeNode l,TreeNode r){
if(l==null && r==null){
return true;}
if(l==null || r==null || l.val!=r.val){
return false;
}
return mirrorTree(l.left,r.right)&&mirrorTree(l.right,r.left);
}
public boolean isSymmetric(TreeNode root) {
if(root==null) return true;
return mirrorTree(root.left,root.right);
}
}