二叉树的反转,递归实现和非递归实现。

package com.alg;

import java.util.Stack;

/**
 * Created by lchli on 2016/3/5.
 */
public class BTreeRevert {

    public static class Node {
        public Node left;
        public Node right;
        public Object data;
    }

    /**
     * 递归实现。
     *
     * @param root
     */
    public static void recusiveRevert(Node root) {
        if (root == null) {
            return;
        }
        swap(root);
        recusiveRevert(root.left);
        recusiveRevert(root.right);

    }

    /**
     * 非递归实现。
     *
     * @param root
     */
    public static void stackRevert(Node root) {
        if (root == null) {
            return;
        }
        Stack stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node current = stack.pop();
            swap(current);
            if (current.left != null) {
                stack.push(current.left);
            }
            if (current.right != null) {
                stack.push(current.right);
            }
        }

    }

    private static void swap(Node root) {
        Node tmp = root.left;
        root.left = root.right;
        root.right = tmp;
    }

    /**
     * test.前序输出。
     *
     * @param root
     */
    public static void preorderOutput(Node root) {
        if (root == null) {
            return;
        }
        System.out.print(root.data);
        preorderOutput(root.left);
        preorderOutput(root.right);

    }
}

你可能感兴趣的:(算法)