[LeetCode]101. 对称二叉树(java实现)递归
1. 题目
2. 读题(需要重点注意的东西)
思路(递归):
构建一颗相同的子树,然后root1向左遍历的时候,root2向右遍历;root1向右遍历的时候,root2向左遍历。然后判断两指针是否为空、或者值是否相同即可。
3. 解法
---------------------------------------------------解法---------------------------------------------------:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return dfs(root.left,root.right);
}
private boolean dfs(TreeNode root1,TreeNode root2){
// 两个节点都为null,成立
if(root1 == null && root2 == null) return true;
// 只有一个节点为null或者两个节点的值不相同,不成立
if(root1 == null || root2 == null || root1.val != root2.val) return false;
// 递归遍历左右子树
return dfs(root1.left,root2.right) && dfs(root1.right,root2.left);
}
}
可能存在的问题: