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;
            }
        }
    }
  • 相关阅读:
    Bw树:新硬件平台的B树(内存数据库中的b树索引)
    SQL Server 列存储索引强化
    SQL Server Column Store Indeses
    我了解的数据库事务复制
    [MySQL Reference Manual] 10 全球化
    [20141208]数据库复制并不会复制索引创建删除
    10个超赞的jQuery图片滑块动画
    推荐20款JavaScript框架给前端开发者
    7个华丽的基于Canvas的HTML5动画
    10个非常炫酷的jQuery相册动画赏析
  • 原文地址:https://www.cnblogs.com/ysw-go/p/11833201.html
Copyright © 2011-2022 走看看