欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

leetcode 101. 对称二叉树 递归解法

程序员文章站 2022-03-13 07:58:54
题目思路一开始想要层序遍历二叉树,然后判断每一层是否回文,写着写着发现这样太麻烦了,看了评论区别人的递归解法,才写出来的。二叉树的四种遍历方法:https://www.cnblogs.com/du001011/p/11229170.html二叉树的层序遍历public class TreeNode { public int data; public TreeNode leftChild; public TreeNode rightChild; public T...

题目

leetcode 101. 对称二叉树 递归解法

思路

一开始想要层序遍历二叉树,然后判断每一层是否回文,写着写着发现这样太麻烦了,看了评论区别人的递归解法,才写出来的。

二叉树的四种遍历方法:
https://www.cnblogs.com/du001011/p/11229170.html

二叉树的层序遍历

public class TreeNode {
    public int data;
    public TreeNode leftChild;
    public TreeNode rightChild;

    public TreeNode(int data){
        this.data = data;
    }
}

public static void levelOrder(TreeNode root){
    LinkedList<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while(!queue.isEmpty()){
        root = queue.pop();
        System.out.print(root.data+" ");
        if(root.leftChild!=null) queue.add(root.leftChild);
        if(root.rightChild!=null) queue.add(root.rightChild);
    }
}

题解(递归解法)

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    @Override
    public String toString() {
        return "" + val;
    }
}


class Solution {
    // 测试用例
    //             1
    //            / \
    //           2   2
    //          / \ / \
    //         3  4 4  3
    public static void main(String[] args) {

        Solution solution = new Solution();
        TreeNode n1 = new TreeNode(1);
        TreeNode n21 = new TreeNode(2);
        TreeNode n22 = new TreeNode(2);
        TreeNode n31 = new TreeNode(3);
        TreeNode n32 = new TreeNode(4);
        TreeNode n33 = new TreeNode(4);
        TreeNode n34 = new TreeNode(3);
        n1.left = n21;
        n1.right = n22;
        n21.left = n31;
        n21.right = n32;
        n22.left = n33;
        n22.right = n34;

        boolean res = solution.isSymmetric(n1);
        System.out.println(res);
    }

    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        } else {
            return is(root.left, root.right);
        }
    }

    private boolean is(TreeNode n1, TreeNode n2) {
        if (n1 == null || n2 == null) {
            return n1 == n2;
        } else {
            return n1.val == n2.val && is(n1.left, n2.right) && is(n1.right, n2.left);
        }
    }
}

leetcode 101. 对称二叉树 递归解法

本文地址:https://blog.csdn.net/sinat_42483341/article/details/107282454