Skip to content

Latest commit

 

History

History
55 lines (50 loc) · 1.35 KB

二叉树的镜像.md

File metadata and controls

55 lines (50 loc) · 1.35 KB

题目描述

请完成一个函数,输入一颗二叉树,请函数输出它的镜像。二叉树节点的定义如下:

public class BinaryTreeNode {
    double value;
    BinaryTreeNode left;
    BinaryTreeNode right;
}

offer27

测试用例

  • 功能测试(普通的二叉树;二叉树的所有节点都没有左子树或者右子树;只有一个节点的二叉树)
  • 特殊输入测试(二叉树的根节点为空指针)

题目考点

  • 考察应聘者对二叉树的理解。
  • 考察应聘者的思维能力,可以通过画图使问题形象化。

解题思路

我们递归交换左右节点即可。

自己解题

/**
 * 二叉树的镜像
 *
 * @Author rex
 * 2018/8/2
 */
public class Solution {
    /**
     * 自己解法
     * 递归
     * @param root
     */
    public void mirror(BinaryTreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null || root.right != null) {
            BinaryTreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            mirror(root.left);
            mirror(root.right);
        }
    }
}

参考解题

参考自己解题

补充

思路比代码更重要,所以在写代码之前一定要先想请思路。