• Symmetric Tree


    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
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     * 非递归的解法,可以用两个双端队列做层序遍历,然后队列从两端弹出元素,两端元素相等说明是对称
     */
    public class Solution {
        public boolean isSymmetricHelper(TreeNode r1, TreeNode r2) {
            //左右半支到叶子节点的时候 判断相等
            if (r1 == null && r2 == null) return true;
            if (r1 == null && r2 != null) return false;
            if (r1 != null && r2 == null) return false;
            if (r1.val != r2.val) return false;
            //左半支的左子树 和右半支的右子树比较相等 左半支的右子树 和右半支的左子树比较相等
            return isSymmetricHelper(r1.left, r2.right) && isSymmetricHelper(r1.right,r2.left);
        }
    
        public boolean isSymmetric(TreeNode root) {
            if (root==null){
                return true;
            }
            if (root.left==null||root.right==null){
                return root.left == root.right;
            }
            return isSymmetricHelper(root.left,root.right);
        }
    }
  • 相关阅读:
    扫雷游戏
    打地鼠Demo
    Game2048
    蛇形矩阵
    约瑟夫环
    二分法查找
    动态规划之防卫导弹
    动态规划之0-1背包问题
    回溯算法之火力网
    回溯算法之8皇后问题
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506857.html
Copyright © 2020-2023  润新知