二叉树的镜像对称实现方式(递归和循环栈)

首先初始化一棵树

 1 public class Node {
 2     //数据
 3     private int data;
 4     //左孩子
 5     private Node leftNode;
 6     //右孩子
 7     private Node rightNode;
 8     public Node(int data, Node leftNode, Node rightNode){
 9         this.data = data;
10         this.leftNode = leftNode;
11         this.rightNode = rightNode;
12     }
13 
14     public int getData() {
15         return data;
16     }
17     public void setData(int data) {
18         this.data = data;
19     }
20     public Node getLeftNode() {
21         return leftNode;
22     }
23     public void setLeftNode(Node leftNode) {
24         this.leftNode = leftNode;
25     }
26     public Node getRightNode() {
27         return rightNode;
28     }
29     public void setRightNode(Node rightNode) {
30         this.rightNode = rightNode;
31     }
32 }
 1 /**
 2      * 初始化二叉树
 3      * @return
 4      */
 5     public Node init() {
 6         Node I = new Node(8, null, null);
 7         Node H = new Node(4, null, null);
 8         Node G = new Node(2, null, null);
 9         Node F = new Node(7, null, I);
10         Node E = new Node(5, H, null);
11         Node D = new Node(1, null, G);
12         Node C = new Node(9, F, null);
13         Node B = new Node(3, D, E);
14         Node A = new Node(6, B, C);
15         //返回根节点
16         return A;
17     }

使用递归实现的镜像对称

 1 //镜像对称(递归实现)
 2     public void mirrorRecursively(Node root){
 3         if(root == null){ //没有树直接返回
 4             return;
 5         }
 6         if(root.getLeftNode() == null && root.getRightNode() == null){ //如果左右结点为空,也直接返回
 7             return;
 8         }
 9         Node pTemp = root.getLeftNode(); //交换树的左右结点
10         root.setLeftNode(root.getRightNode());
11         root.setRightNode(pTemp);
12         if(root.getLeftNode()!=null){ //如果左结点不为空,继续
13             mirrorRecursively(root.getLeftNode());
14         }
15         if(root.getRightNode() != null){ //如果右结点不为空,继续
16             mirrorRecursively(root.getRightNode());
17         }
18     }

使用循环栈实现的镜像对称

 1 //镜像对称(循环栈实现)
 2     public void mirror2(Node root){
 3         if(root == null){ //没有树直接返回
 4             return;
 5         }
 6         Stack stack = new Stack<>();
 7         stack.push(root);
 8         while (!stack.isEmpty()){
 9             Node pop = stack.pop();
10             if (pop.getLeftNode() != null && pop.getRightNode() != null){
11                 Node pTemp = root.getLeftNode(); //交换树的左右结点
12                 root.setLeftNode(root.getRightNode());
13                 root.setRightNode(pTemp);
14             }
15             if(root.getLeftNode()!=null){ //如果左结点不为空,压入栈
16                 stack.push(root.getLeftNode());
17             }
18             if(root.getRightNode() != null){ //如果右结点不为空,压入栈
19                 stack.push(root.getRightNode());
20             }
21         }
22     }

转载于:https://www.cnblogs.com/zsh-blogs/p/10740143.html

你可能感兴趣的:(二叉树的镜像对称实现方式(递归和循环栈))