zoukankan      html  css  js  c++  java
  • Leetcode题目101.对称二叉树(简单)

    题目描述:

    给定一个二叉树,检查它是否是镜像对称的。

    例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
    
        1
       / 
      2   2
     /  / 
    3  4 4  3
    但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
    
        1
       / 
      2   2
          
       3    3
    说明:
    
    如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

    思路解析:

    思路一:对二叉树进行中序遍历,判断节点值是否对称分布(LeetCode测试用例未通过,但本地测试通过)

        public static boolean isSymmetric(TreeNode root) {
    
            List<Integer> res = new ArrayList<>();
    
            dfsTraverse(root, res);
    
            return validate(res);
        }
    
        private static boolean validate(List<Integer> res) {
    
            for (int i = 0; i < res.size() / 2; i++) {
                if (!res.get(i).equals(res.get(res.size() - 1 - i))) {
                    return false;
                }
            }
            return true;
        }
    
        private static void dfsTraverse(TreeNode root, List<Integer> res) {
    
            if (root == null) {
                res.add(Integer.MAX_VALUE);
                return;
            }
            dfsTraverse(root.left, res);
            res.add(root.val);
            dfsTraverse(root.right, res);
        }

    思路二:递归

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        
     public static boolean isSymmetric(TreeNode root) {
    
            if (root == null) {
                return true;
            }
    
            return validate(root.left, root.right);
        }
    
        private static boolean validate(TreeNode pNode, TreeNode qNode) {
    
            if (pNode == null && qNode == null) {
                return true;
            }
            if (pNode != null && qNode != null && pNode.val == qNode.val) {
    
                return validate(pNode.left, qNode.right) && validate(pNode.right, qNode.left);
    
            } else {
                return false;
            }
        }
    }
  • 相关阅读:
    目标检测应用化之web页面(YOLO、SSD等)
    传统候选区域提取方法
    非极大值抑制(Non-Maximum Suppression,NMS)
    Darknet windows移植(YOLO v2)
    线性判别分析 LDA
    SVM 支持向量机
    特征-相似度衡量
    布隆过滤器 Bloom Filter
    聚类算法
    图论--最大流
  • 原文地址:https://www.cnblogs.com/ysw-go/p/11833201.html
Copyright © 2011-2022 走看看