Java反转二叉树

// 二叉树节点定义
public class BinaryTreefanzhuan {

class TreeNode{
  int value;
  TreeNode left;
  TreeNode right;
}

// 递归
public static TreeNode invertNode(TreeNode root){
  if (root == null) return null;
   TreeNode temp = root.left;
  root.left = invertNode(root.right);
  root.right = invertNode(temp);
  return root;
}

// 非递归
//交换左右节点后,将这个两个节点放入队列,继续下一层交换
public static TreeNode invertNode2(TreeNode root){
  if (root == null) return null;
  Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
  while(!nodeQueue.isEmpty()){
    TreeNode current = nodeQueue.poll();
    TreeNode temp = current.left;
    current.left = current.right;
    current.right = temp;
    if (current.left != null) nodeQueue.add(current.left);
    if (current.right != null) nodeQueue.add(current.right);
    }
  return root;
}

上一篇:Apache 安装与配置


下一篇:DOM综合案例、SAX解析、StAX解析、DOM4J解析