美文网首页剑指offer——Java实现
面试题19:二叉树的镜像

面试题19:二叉树的镜像

作者: _minimal | 来源:发表于2016-10-08 17:10 被阅读23次

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

代码实现

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null || (root.left == null && root.right == null))
            return;
        
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        Mirror(root.left);
        Mirror(root.right);
    }
}

主要思路

很简单的递归题,三步走:
(1)特殊输入的判断
(2)交换根结点的左右孩子结点
(3)递归访问所有结点(每访问一个结点的时候,都会把它的左右孩子交换)

相关文章

网友评论

    本文标题:面试题19:二叉树的镜像

    本文链接:https://www.haomeiwen.com/subject/itwuyttx.html