The sword refers to the Offer-Question 28 (Java Edition): Symmetric Binary Tree

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Question : Symmetric Binary Tree
Please implement a function to determine whether a binary tree is symmetric. A binary tree is symmetric if it is the same as its mirror image.
For example:
Symmetric binary tree: make a vertical line with the root node, and the left and right child nodes are symmetrical about the vertical line

//            10
//         /      \
//        6        6
//       /\        /\
//      5  7      7  5
位置:   2  1      1  2

Main idea : Recursively judge whether the nodes of each layer are symmetrical, that is, take the root node as the center, divide the tree into left and right halves, and judge each position of the left half ( the position is the length of the node from the center ). Whether the node is equal to the node at the corresponding position in the right half. Therefore, the left node of the left half is compared to the right node of the right half, and vice versa.

Key Points : Recursion, Symmetric Binary Tree

Time complexity : O(n)

public class SymmetricalTree
{
    public static void main(String[] args)
    {
        TreeNode root = TreeNode.generateSymmetricalTree();
        System.out.println(isSymmetrical(root)); //true
    }

    private static boolean isSymmetrical(TreeNode pRoot)
    {
        return isSymmetric(pRoot, pRoot);
    }

    private static boolean isSymmetric(TreeNode tree1, TreeNode tree2)
    {
        if (tree1 == null && tree2 == null) return true;
        if (tree1 == null || tree2 == null) return false;
        if (tree1.val != tree2.val) return false;
        //左节点和右节点相等
        return isSymmetric(tree1.left, tree2.right)
                && isSymmetric(tree1.right, tree2.left);
    }
}

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

    TreeNode(int x)
    {
        val = x;
    }

//            10
//         /      \
//        6        6
//       /\        /\
//      5  7      7  5
    /**
     * 生成对称二叉树
     * @return
     */
    public static TreeNode generateSymmetricalTree()
    {
        TreeNode root = new TreeNode(10);
        TreeNode node6 = new TreeNode(6);
        TreeNode node62 = new TreeNode(6);
        TreeNode node5 = new TreeNode(5);
        TreeNode node7 = new TreeNode(7);
        TreeNode node72 = new TreeNode(7);
        TreeNode node52 = new TreeNode(5);
        connectNode(root, node6, node62);
        connectNode(node6, node5, node7);
        connectNode(node62, node72, node52);
        return root;
    }
    private static void connectNode(TreeNode root, TreeNode left, TreeNode right)
    {
        root.left = left;
        root.right = right;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325895974&siteId=291194637