Binary Tree Mirroring (Java implementation) __java

Source: Internet
Author: User

Sword refers to the offer face question 19

New Ket Network realism address: https://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011

Time limit: 1 seconds space limit: 32768K algorithm knowledge video explanation operation of the given two fork tree, transform it into the source binary tree mirroring.
Enter a description:

Binary tree Mirroring definition: source binary tree 
    	    8
    	   /  \
    	  6
    	 /\  /\
    	5  7 9
    	Mirror binary tree
    	    8
    	   /  \   6
    	 /  //
    	9 7  5

Import Java.util.Stack;

public class Demo2 {
	 /* Method One: Recursive implementation
	 * When the recursion depth is deep enough, the computer crashes/public
	 void Mirror (TreeNode root) {
		 if (root==null)
			 return;
		 TreeNode Temp=root.left;
		 Root.left=root.right;
		 Root.right=temp;
		 Mirror (root.left);
		 Mirror (root.right);
	 }
	/
	 * Method Two: Loop implementation ———— use stack
	/public void Mirror_cir (TreeNode root) {
		if (root==null) return
			;
		Stack<treenode> stack=new stack<treenode> ();
		Stack.push (root);
		while (!stack.isempty ()) {
			TreeNode node=stack.pop ();
			if (node.left!=null| | Node.right!=null) {
				TreeNode temp=node.left;
				Node.left=node.right;
				node.right=temp;
			}
			if (node.left!=null)
				Stack.push (node.left);
			if (node.right!=null)
				Stack.push (node.right);
			
		}
		
	}
	Class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;

	    Public TreeNode (int val) {
	        this.val = val;}}}







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.