【题目】二叉树的镜像
【思路】方法一:采用递归方式进行交换,先交换根节点的左右节点,接着交换左右结点的左右结点
方法二:采用非递归方式,即依次遍历左右子树结点依次交换,采用栈操作方式stack
1 package com.exe4.offer; 2 import java.util.Stack; 3 4 /** 5 * 16【题目】二叉树的镜像 6 * 【思路】方法一:采用递归方式进行交换,先交换根节点的左右节点,接着交换左右结点的左右结点 7 * 方法二:采用非递归方式,即依次遍历左右子树结点依次交换,采用栈操作方式stack 8 * @author WGS 9 * 10 */ 11 public class TreeMirror { 12 //二叉树结点定义 13 public static class TreeNode { 14 int val = 0; 15 TreeNode left = null; 16 TreeNode right = null; 17 18 public TreeNode(int val) { 19 this.val = val; 20 21 } 22 23 } 24 //采用递归方式进行交换,先交换根节点的左右节点,接着交换左右结点的左右结点 25 public void mirrorExchange(TreeNode node){ 26 if(node==null || node.left==null || node.right==null){ 27 return; 28 } 29 //开始交换根节点的左右结点 30 TreeNode tempNode=null; 31 tempNode=node.left; 32 node.left=node.right; 33 node.right=tempNode; 34 35 //继续交换 36 if(node.left!=null) 37 mirrorExchange(node.left); 38 if(node.right!=null) 39 mirrorExchange(node.right); 40 } 41 //采用非递归方式,即依次遍历左右子树结点依次交换,采用栈操作方式s 42 public void mirrorExchange2(TreeNode root){ 43 if(root==null || root.left==null || root.right==null){ 44 return; 45 } 46 Stack<TreeNode> stack = new Stack<TreeNode>(); 47 stack.push(root); 48 while(!stack.isEmpty()){ 49 TreeNode node=stack.pop(); 50 //交换左右结点 51 TreeNode temp=node.left; 52 node.left=node.right; 53 node.right=temp; 54 //继续遍历下一个左右结点 55 if(node.left!=null) 56 stack.push(node.left); 57 if(node.right!=null) 58 stack.push(node.right); 59 } 60 } 61 62 //前序遍历1 63 public void preInOreder(TreeNode T){ 64 if(T==null) return; 65 System.out.println(T.val); 66 preInOreder(T.left); 67 preInOreder(T.right); 68 } 69 //前序遍历2 70 public void preOrderTarverse(TreeNode root) { 71 Stack<TreeNode> s = new Stack<TreeNode>(); 72 while (root != null || !s.isEmpty()) { 73 //遍历左子树 74 while (root != null) { 75 System.out.println(root.val); 76 s.push(root); 77 root = root.left; 78 } 79 // 左子树遍历结束,继续遍历右子树 80 if (!s.isEmpty()) { 81 root = s.pop(); 82 root = root.right; 83 } 84 } 85 } 86 87 public static void main(String[] args) { 88 TreeNode root = new TreeNode(8); 89 TreeNode node1 = new TreeNode(6); 90 TreeNode node2 = new TreeNode(10); 91 TreeNode node3 = new TreeNode(5); 92 TreeNode node4 = new TreeNode(7); 93 TreeNode node5 = new TreeNode(9); 94 TreeNode node6 = new TreeNode(11); 95 96 root.left = node1; 97 root.right = node2; 98 node1.left = node3; 99 node1.right = node4; 100 node2.left = node5; 101 node2.right = node6; 102 103 TreeMirror r = new TreeMirror(); 104 r.mirrorExchange2(root); 105 106 r.preOrderTarverse(root); 107 } 108 }
时间: 2024-10-09 03:54:07