Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3和same tree那道题思路一样, 终止条件还是1.左子树为空 右子树不为空 2. 右子树为空 左子树不为空 3. 左子树的值和右子树不同
一颗树对称其实就是看左右子树是否对称,一句话就是左同右,右同左,结点是对称的相等。
算法的时间复杂度是树的遍历O(n),空间复杂度同样与树遍历相同是O(logn)
public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return helper(root.left, root.right); } public boolean helper(TreeNode node1, TreeNode node2) { if (node1 == null && node2 == null) { return true; } if (node1 == null || node2 == null) { return false; } if (node1.val != node2.val) {//if true 继续递归 return false; } return helper(node1.left, node2.right) && helper(node2.left, node1.right); } }
没有评论:
发表评论