二叉树的镜像
剑指offer-每日一练
二叉树的镜像
看到这个算法,首先想到的是递归;
package practise;
import structure.TreeNode;
/**
* @author :lonus_lan
* @date :Created in 2020/1/13 19:33
* @description: this is the mirror of the binary tree
* @modified By:
*/
public class TheMirrorOfBinaryTree {
public static void mirrorRecursive(TreeNode<Integer> root){
//鲁棒性
if(root == null || (root.left == null && root.right == null)){
return;
}
TreeNode<Integer> nodeTemp = root.left;
root.left = root.right;
root.right = nodeTemp;
mirrorRecursive(root.left);
mirrorRecursive(root.right);
}
public static void main(String[] args){
TreeNode<Integer> root = new TreeNode<>(6);
root.left =new TreeNode<>(8);
root.right = new TreeNode<>(10);
root.left.left = new TreeNode<>(4);
root.left.right = new TreeNode<>(1);
root.right.left = new TreeNode<>(2);
root.right.right = new TreeNode<>(3);
System.out.println(root);
mirrorRecursive(root);
System.out.println(root);
}
}
以后尝试下非递归;
未完待续。
Always fail, never succeed