Prove safety offer: a binary image (recursively, leetcode 226)

topic:

Operation of a given binary tree, the binary tree is converted into a source image.

Mirroring definition of binary tree: 
Source binary 
    	    8 
    	   / \ 
    	  610 
    	 / \ / \ 
    	57911 
mirror binary 
    	    8 
    	   / \ 
    	  106 
    	 / \ / \ 
    	11975

answer:

Solution one:

Recursively, as follows:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null)){
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        Mirror(root.left);
        Mirror(root.right);
        return ;
        
    }
}

Solution two:

Iterative method, similar to the depth-first search, use the queue, as follows:

public class Solution {
    public void Mirror(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null)){
            return;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.remove();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if(node.left!=null) queue.add(node.left);
            if(node.right!=null) queue.add(node.right);
        }
        return ;
        
    }
}

 

Published 92 original articles · won praise 2 · Views 8409

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104867128