JZ18 二叉树的镜像,递归&迭代
二叉树的镜像
http://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011
解法一:递归
public class Solution { public void Mirror(TreeNode root) { root=reverse(root); } TreeNode reverse(TreeNode root){ if(root==null) return root; TreeNode t=root.left; root.left=reverse(root.right); root.right=reverse(t); return root; } }
解法二:迭代
import java.util.*; public class Solution { public void Mirror(TreeNode root) { if(root==null) return; LinkedList<TreeNode> q=new LinkedList<>(); q.add(root); while(!q.isEmpty()){ TreeNode curr=q.poll(); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); TreeNode t=curr.left; curr.left=curr.right; curr.right=t; } } }