LeetCode 101. Symmetric Tree 对称二叉树

题目

https://leetcode.com/problems/symmetric-tree/description/

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.

 

讲解

我们需要一个辅助函数isMirror(TreeNode node1, TreeNode node2)来帮助解决问题。

isMirror(TreeNode node1, TreeNode node2)在以下条件下返回true:

  1. 当node1和node2都为null时
  2. 当node1和node2都不为null, node1和node2的值相等。并且node1的左子树是 node2右子树的镜像,node2的左子树是node1右子树的镜像。

视频教学

Java参考代码

/**
 * 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 isMirror(root.left, root.right);
    }
    
    private boolean isMirror(TreeNode node1, TreeNode node2) {
        if (node1 == null && node2 == null) {
            return true;
        }
        
        if (node1 == null || node2 == null) {
            return false;
        }
        
        if (node1.val != node2.val) {
            return false;
        }        
        
        return node1.val == node2.val && isMirror(node1.left, node2.right) && isMirror(node1.right, node2.left);
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注