Skip to content

Latest commit

 

History

History
75 lines (64 loc) · 2.29 KB

101_对称二叉树.md

File metadata and controls

75 lines (64 loc) · 2.29 KB
import java.util.*;


/**
 * @author : xfhy
 * Create time : 2020年08月08日16:33:20
 * Description : 101. 对称二叉树
 * source : https://leetcode-cn.com/problems/symmetric-tree/
 */
public class Solution {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * 思路: 利用左子树和右子树相等,递归遍历.在遍历时需要2个引用,left表示左子树,right表示右子树,
     * 需要比较左子树的左孩子与右子树的右孩子 && 比较左子树的右孩子与右子树的左孩子
     */
    public static boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return dfs(root, root);
    }

    public static boolean dfs(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        return dfs(left.left, right.right) && dfs(left.right, right.left);
    }

    public static TreeNode createBinaryTree(LinkedList<Integer> inputList) {
        if (inputList == null || inputList.isEmpty()) {
            return null;
        }
        TreeNode node = null;
        Integer data = inputList.removeFirst();
        if (data != null) {
            node = new TreeNode(data);
            node.left = createBinaryTree(inputList);
            node.right = createBinaryTree(inputList);
        }
        return node;
    }

    public static void main(String[] args) {
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(5, 4, 11, 7, null, null, 2, null, null, null, 8, 13, null, null, 4,
                5, null, null, 1));*/
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null,
                null, 8, null, 4));*/
        LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 9, null, null, 20, 15, null, null, 7));
        LinkedList<Integer> integers2 = new LinkedList<>(Arrays.asList(1, 2, null, null, 2));
        TreeNode binaryTree = createBinaryTree(integers);

        System.out.println(isSymmetric(binaryTree));
    }

}