【一次过】Lintcode 1360. 对称树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85334888

给定二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。

样例

例如,这个二叉树“{1,2,2,3,4,4,3}”是对称的:

    1
   / \
  2   2
 / \ / \
3  4 4  3

的英文然如下  {1,2,2,#,3,#,3} 不是:

    1
   / \
  2   2
   \   \
   3    3

注意事项

如果您可以同时用递归和迭代解决它,那么奖励分数。


解题思路:

先对左子树反转,参考:Lintcode 175. 翻转二叉树,然后比较两子树是否相等即可,参考:Lintcode 469. Same Tree

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: root of the given tree
     * @return: whether it is a mirror of itself 
     */
    public boolean isSymmetric(TreeNode root) {
        // Write your code here
        if(root == null)
            return true;
        
        invertTree(root.left);
        
        return isSame(root.left, root.right);
    }
    
    private void invertTree(TreeNode root){
        if(root == null)
            return;
            
        invertTree(root.left);
        invertTree(root.right);
        
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
    
    private boolean isSame(TreeNode node1, TreeNode node2){
        if(node1 == null && node2 == null)
            return true;
            
        if(node1 == null || node2 == null)
            return false;
        
        if(isSame(node1.left, node2.left) && isSame(node1.right, node2.right))
            return (node1.val == node2.val) ? true : false;
            
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/85334888