算法复习:二叉树的镜像

xiaoxiao2021-02-27  192

题目描述

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

输入描述:

二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5 解题思路: 从上往下不断交换左右子树即可,注意特殊输入 代码: /** 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)return; if(root.left == null && root.right == null)return; TreeNode temp = root.left; root.left = root.right; root.right = temp;   if(root.right != null) Mirror(root.right); if(root.left != null) Mirror(root.left);     } } 但是,这种方法效率很低,面试官应该会希望看到我们使用更高效的方法。观察一下规律,假如出现的是12345,那么从10000到12345之间的第一位都是1,出现的次数就是后面的数字加上1,后面的数字又可以使用递归继续算。具体的方法参考《剑指offer》
转载请注明原文地址: https://www.6miu.com/read-9148.html

最新回复(0)