LeetCode 101. Symmetric Tree
原题链接
简单
作者:
Ccc1Z
,
2020-07-15 19:22:13
,
所有人可见
,
阅读 340
思路
- 判断二叉树是否镜像
- 抓住镜像的条件进行BFS
- 镜像及左子树根节点.val == 右子树根节点.val
- 然后递归处理
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return dfs(root.left,root.right);
}
private boolean dfs(TreeNode left,TreeNode right){
if(left == null || right == null)
return left == null && right == null;
return left.val == right.val && dfs(left.left,right.right) && dfs(left.right,right.left);
}
}