剑指offer--面试题19:二叉树的镜像--Java实现
来源:互联网 发布:sybase数据库win7 64 编辑:程序博客网 时间:2024/05/22 05:24
题目描述:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
解题思路:
我们先前序遍历这棵树的每个结点,如果这个结点有子结点,就交换它的两个子结点。当交换完所有非叶子结点的左右子结点后,就得到了树的镜像。
这里采用了递归方式和非递归方式。
import java.util.Stack;public class MirrorRecursivelyTest { static class Node{ int key; Node left; Node right; Node(int key){ this.key = key; } } public static void mirrorRecursively(Node root){ if(root == null){ return; } if(root.left == null && root.right == null){ return; } Node node = root.left; root.left = root.right; root.right = node; if(root.left != null){ mirrorRecursively(root.left); } if(root.right != null){ mirrorRecursively(root.right); } } //非递归实现,要借助栈 public static void mirrorNoneRecurvisely(Node root){ Stack<Node> stack = new Stack<Node>(); stack.add(root); while(!stack.isEmpty()){ Node node = stack.pop(); if(node.left != null || node.right != null){ Node tmp = node.left; node.left = node.right; node.right = tmp; } if(node.left != null){ stack.push(node.left); } if(node.right != null){ stack.push(node.right); } } } //打印树 public static void printTree(Node node){ if(node == null){ return; } System.out.println(node.key); printTree(node.left); printTree(node.right); } public static void main(String[] args) { Node root = new Node(8); Node node8 = new Node(8); Node node7 = new Node(7); root.left = node8; root.right = node7; Node node9 = new Node(9); node8.left = node9; Node node2 = new Node(2); node8.right = node2; Node node4 = new Node(4); Node node72 = new Node(7); node2.left = node4; node2.right = node72; //mirrorRecursively(root); mirrorNoneRecurvisely(root); printTree(root); }}
测试数据如下图
0 0
- 剑指offer--面试题19:二叉树的镜像--Java实现
- 剑指Offer:面试题19——二叉树的镜像(java实现)
- [剑指offer][面试题19]二叉树的镜像
- 【剑指offer】面试题19:二叉树的镜像
- 剑指offer 面试题19 二叉树的镜像
- 剑指Offer:面试题19 二叉树的镜像
- 《剑指Offer》面试题19:二叉树的镜像
- 剑指offer-面试题19:二叉树的镜像
- 剑指Offer----面试题19:二叉树的镜像
- 剑指offer面试题19:二叉树的镜像
- 剑指offer面试题19:二叉树的镜像
- 剑指offer面试题19:二叉树的镜像
- 剑指offer--面试题19:二叉树的镜像
- 剑指offer-面试题19-二叉树的镜像
- 【剑指offer】面试题19:二叉树的镜像
- 【面试题】剑指Offer-19-二叉树的镜像
- 剑指offer-面试题19-二叉树的镜像
- 剑指offer-面试题 19:二叉树的镜像
- webbrowser处理HTML Element Event事件
- OGG参数详解
- HTTP错误
- Java Web开发相关连接
- 选择排序
- 剑指offer--面试题19:二叉树的镜像--Java实现
- C++第12章项目,ATM机模拟队列。
- OGG同步数据方法
- 关于selector失效的问题
- C++下高效率int转成string
- block IO层框架分析2
- C#不同类间通过事件传递参数
- 感知机学习算法的原始形式
- Opencv中常用库文件名称