数据结构与算法_剑指Offer19_二叉树的镜像_JAVA实现

2020.05.05

题目:

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

解题思路:

其实类似二叉查找树的遍历思路,以前序遍历为例,交换所有非叶子结点的左右结点,可以对比order()与mirror()两个方法。

package offer19;

class Node {
    int value;
    Node leftChild;
    Node rightChild;
    
	public Node(int value) {
		super();
		this.value = value;
	}
    
	public Node() {
		// TODO 自动生成的构造函数存根
	}
}

class Tree{
	Node rootNode = null;
	
	public void insert(Node newNode) {
		Node currentNode = rootNode;
		Node parentNode  = null;
		
		if(rootNode == null) {
			rootNode = newNode;
			return;
		}
		
		while (true) {
			parentNode = currentNode;
			if(currentNode.value < newNode.value){
				currentNode = currentNode.rightChild;
				if(currentNode == null) {
					parentNode.rightChild = newNode;
					return;
				}
			}else {
				currentNode = currentNode.leftChild;
				if(currentNode == null) {
					parentNode.leftChild = newNode;
					return;
				}
			}
		}
	}
	
	public void order(Node rootNode) {
		Node currentNode = rootNode;
		if (currentNode != null) {
			order(currentNode.leftChild);
			System.out.print(currentNode.value);
			order(currentNode.rightChild);
		}
	}
	
	public void mirror(Node rootNode) {
		Node currentNode = rootNode;
		if (currentNode != null) {
			if(!(currentNode.leftChild == null && currentNode.rightChild == null)) {
				Node tempNode = currentNode.leftChild;
				currentNode.leftChild = currentNode.rightChild;
				currentNode.rightChild = tempNode;
			}
			mirror(currentNode.leftChild);
			mirror(currentNode.rightChild);
		}
	}
}

public class Test {
	public static void main(String[] args) {
		//      8
		//    /    \
		//   6     10
		//  / \    / \
		// 5   7  9   11
		Tree testTree1 = new Tree();
		testTree1.insert(new Node(8));
		testTree1.insert(new Node(6));
		testTree1.insert(new Node(10));
		testTree1.insert(new Node(5));
		testTree1.insert(new Node(7));
		testTree1.insert(new Node(9));
		testTree1.insert(new Node(11));
		testTree1.order(testTree1.rootNode);
		testTree1.mirror(testTree1.rootNode);
		System.out.println();
		testTree1.order(testTree1.rootNode);
		
		// 0
        //  \
        //   2
        //    \
        //     4
        //      \
        //       6
        //        \
        //         8
		System.out.println();
		Tree testTree2 = new Tree();
		testTree2.insert(new Node(0));
		testTree2.insert(new Node(2));
		testTree2.insert(new Node(4));
		testTree2.insert(new Node(6));
		testTree2.insert(new Node(8));
		testTree2.order(testTree2.rootNode);
		testTree2.mirror(testTree2.rootNode);
		System.out.println();
		testTree2.order(testTree2.rootNode);
		
	}
}

你可能感兴趣的:(数据结构与算法,算法,数据结构,二叉树,java)