[LeetCode]Symmetric Tree

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


Question
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:

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.


本题难度Easy。

递归

【复杂度】
时间 O(N) 空间 O(h) 递归栈空间

【思路】
其实和Same Tree写法是一样的,Same Tree是比较两个节点的两个左边,然后再比较两个节点的两个右边。而对称树是要判断左节点的左节点和右节点的右节点相同(外侧),左节点的右节点和右节点的左节点相同(内侧)。不过对称树是判断一棵树,我们要用Same Tree一样的写法,就要另写一个可以比较两个节点的函数。

【代码】

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
return helper(root,root);
}
private boolean helper(TreeNode root1,TreeNode root2){
//base case
if(root1==root2&&root1==null)
return true;
if(root1==null||root2==null)
return false;
return root1.val==root2.val&&
helper(root1.left,root2.right)&&
helper(root1.right,root2.left);
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6