zoukankan      html  css  js  c++  java
  • LeetCode 101. Symmetric Tree

    原题链接在这里:https://leetcode.com/problems/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

    题解:

    本题与Same Tree类似。这里比较是否symmetric, 也是用recursion, 需要写一个helper function, 递归调用,每次对称着比较。

    Time Complexity: O(n), n是tree的node数目. Space: O(logn).

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public boolean isSymmetric(TreeNode root) {
    12         if(root == null){
    13             return true;
    14         }
    15         return isSymm(root.left, root.right);
    16     }
    17     
    18     private boolean isSymm(TreeNode p, TreeNode q){
    19         if(p == null && q == null){
    20             return true;
    21         }
    22         if(p == null || q == null){
    23             return false;
    24         }
    25         return p.val == q.val && isSymm(p.left, q.right) && isSymm(p.right, q.left);
    26     }
    27 }
  • 相关阅读:
    react-webpack-express
    React总结和遇到的坑
    vue+node+mongodb实现的功能
    webpack整体了解
    webpack踩坑
    深入了解MongoDB
    实现pdf word在线浏览和下载
    node实现爬虫
    火客声音分析
    抖音二婷衣橱分析
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824989.html
Copyright © 2011-2022 走看看