zoukankan      html  css  js  c++  java
  • 【面试题19】二叉树的镜像

    【题目描述】

    请完成一个函数,输入一个二叉树,该函数输出它的镜像。

    【解决方案】

    即反转二叉树,左右结点互换,用递归解决。

    我的代码实现,仅供参考:

     1         public static BinaryTreeNode ReverseBT(BinaryTreeNode node)
     2         {
     3             if (node == null)
     4             {
     5                 return node;
     6             }
     7 
     8             if (node.Left == null && node.Right == null)
     9             {
    10                 return node;
    11             }
    12 
    13             BinaryTreeNode temp = ReverseBT(node.Left);
    14             node.Left = ReverseBT(node.Right);
    15             node.Right = temp;
    16 
    17             return node;
    18         }

    【本题扩展】

    上面代码使用递归实现的。如果要求用循环,该如何实现?

    一说到递归,必然要想到栈。

    我的代码实现,仅供参考:

     1         public static BinaryTreeNode ReverseBT(BinaryTreeNode root)
     2         {
     3             if (root == null)
     4             {
     5                 return root;
     6             }
     7 
     8             BinaryTreeNode temp = null, node = null;
     9 
    10             Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
    11             stack.Push(root);
    12 
    13             while (stack.Count > 0)
    14             {
    15                 node = stack.Pop();
    16 
    17                 temp = node.Left;
    18                 node.Left = node.Right;
    19                 node.Right = temp;
    20 
    21                 if (node.Left != null)
    22                 {
    23                     stack.Push(node.Left);
    24                 }
    25 
    26                 if (node.Right != null)
    27                 {
    28                     stack.Push(node.Right);
    29                 }
    30             }
    31 
    32             return root;
    33         }
  • 相关阅读:
    开篇之作
    瀑布流特效
    随写
    关于冒泡排序的补充
    New start-开始我的学习记录吧
    java中序列化的简单认识
    我的Python之路
    算法学习笔记
    Leaflet个人封装笔记
    反射获取config实体类属性并赋值
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4803934.html
Copyright © 2011-2022 走看看