树的实现类
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
super();
this.val = val;
this.left = left;
this.right = right;
}
public TreeNode() {
super();
}
}
import java.util.LinkedList;
import java.util.Queue;
public class InvertBinaryTree {
//递归的先序遍历实现
public TreeNode invertTree(TreeNode root) {
if(root!=null){
TreeNode t=root.left;
root.left=root.right;
root.right=t;
invertTree(root.left);
invertTree(root.right);
return root;
}else{
return null;
}
}
//非递归的广度优先遍历实现 - BFS(Breadth First Search)
public TreeNode invertTree_bfs(TreeNode root) {
if(root==null){
return null;
}else{
Queue queue=new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode p=queue.poll();
TreeNode t=p.left;
p.left=p.right;
p.right=t;
if(p.left!=null){
queue.offer(p.left);
}
if(p.right!=null){
queue.offer(p.right);
}
}
return root;
}
}
}