zoukankan      html  css  js  c++  java
  • 101. Symmetric Tree 101.对称树

    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

    典型的因为是形状而递归(recursive)的题目。所以最好写个helper函数吧,更加方便表达。之后的参数可以事无巨细地传进去。这题的递归入口
    就是左边、右边这样
    这种可能是空,不一定有的节点,需要丢到递归函数中。其实这是divide的一部分,只是没有等号罢了。conquer也是一样的具体实现。
    //推测着写。
            if ((root.left.left.val != root.right.right.val)  || (root.left.right.val != root.right.left.val))

     参数最好用root1 root2吧,以免混淆

    参数可以直接是root1 root2两个陌生节点,而不是root。
    所以最后一步就只需要一层root1.left,表示起来更方便

     

    if (root1.val != root2.val)
    return false;
    //只需要返回false的情况,true的情况需要divide后长期考察才行

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public boolean isSymmetric(TreeNode root) {
            //特殊情况
            if (root == null)
                return true;
            
            return helper(root.left, root.right);
        }
        
        public boolean helper(TreeNode root1, TreeNode root2) {
            if ((root1 == null) && (root2 == null))
                return true;
            
            //只有一个为空
            if ((root1 == null) || (root2 == null))
                return false;
            
            //本身左右不相等
            if (root1.val != root2.val)
                return false;
            
            //递归的情况
            return (helper(root1.left, root2.right) && helper(root1.right, root2.left));
        }
    }
    View Code
  • 相关阅读:
    JavaSE 基础 第17节 流程控制之break、continue、return的用法
    JavaSE 基础 第16节 流程控制之循环结构
    JavaSE 基础 第15节 流程控制之选择结构
    JavaSE 基础 第14节 关系运算符、逻辑运算符与三元运算符
    JavaSE 基础 第13节 算术赋值运算符与自增自减运算符
    MySQL4-SQLAlchemy框架实现
    MySQL3>mysql进阶
    MySQL2>常用命令汇集
    MySQL1>概述
    python-协程
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12953003.html
Copyright © 2011-2022 走看看