二叉树的镜像

    科技2022-07-11  96

    1.递归(交换当前节点的左右子节点,然后递归)

    public class Solution { 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); } }

    2.非递归(利用二叉树的层序遍历)

    import java.util.*; public class Solution { public void Mirror(TreeNode root) { if(root==null) return; Queue<TreeNode> list=new LinkedList<>(); list.offer(root); while(!list.isEmpty()){ for(int i=0;i<list.size();i++){ TreeNode cur=list.poll(); TreeNode temp=cur.left; cur.left=cur.right; cur.right=temp; if(cur.left!=null) list.offer(cur.left); if(cur.right!=null) list.offer(cur.right); } } } }

     

    Processed: 0.008, SQL: 8