首页 > 其他 > 详细

Unique Binary Search Trees II

时间:2015-03-23 17:59:15      阅读:252      评论:0      收藏:0      [点我收藏+]

问题来源:https://leetcode.com/problems/unique-binary-search-trees-ii/

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import org.junit.Test;
/**
 * 
 * <p>ClassName UniqueBinarySearchTressII</p>
 * <p>Description Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.
 * For example,
 * Given n = 3, your program should return all 5 unique BST‘s shown below.
 *  1         3     3      2      1
 *   \       /     /      / \       *    3     2     1      1   3      2
 *   /     /       \                  *  2     1         2                 3
 * confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
 * OJ‘s Binary Tree Serialization:
 * The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.
 * Here‘s an example:
 *  1
 * /  *2   3
 *   /
 *  4
 *    *    5
 * The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".</p>
 * @author TKPad wangx89@126.com
 * <p>Date 2015年3月23日 下午4:45:16 </p>
 * @version V1.0.0
 *
 */
public class UniqueBinarySearchTreesII {

    public List<TreeNode> generateTrees(int n) {
        return help(1, n);
    }

    public ArrayList<TreeNode> help(int left, int right) {
        ArrayList<TreeNode> res = new ArrayList<TreeNode>();
        if (left > right) {
            res.add(null);
            return res;
        } else {
            // 左子树小于等于右子树,则分别递归构建两颗子树
            for (int i = left; i <= right; i++) {
                ArrayList<TreeNode> leftList = help(left, i - 1);
                ArrayList<TreeNode> rightList = help(i + 1, right);
                for (int j = 0; j < leftList.size(); j++) {
                    for (int k = 0; k < rightList.size(); k++) {
                        TreeNode root = new TreeNode(i);
                        root.left = leftList.get(j);
                        root.right = rightList.get(k);
                        res.add(root);
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        List<TreeNode> generateTrees = new UniqueBinarySearchTreesII().generateTrees(3);
        System.out.println(generateTrees.size());
        Iterator<TreeNode> iterator = generateTrees.iterator();
        while (iterator.hasNext()) {
            TreeNode next = iterator.next();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            print(next, queue);
            //注意将最后的#移除,因为在层次遍历的时候,可能在最后一个节点后面会加入#,但是#后面没有节点了,所以#也没有什么意义,需要移除
            while (list.get(list.size() - 1).equals("#")) {
                list.remove(list.size() - 1);
            }
            System.out.println(list);
            list.clear();
        }
    }

    static List<String> list = new LinkedList<String>();

    /**
     * 
     * <p>
     * Title: print
     * </p>
     * <p>
     * Description: 层次遍历二叉树,并且当存在空的左子树或右子树时,以#取代
     * </p>
     * 
     * @param root
     *            二叉树的根节点
     * @param queue
     *            暂存左右子树的队列
     *
     */
    public static void print(TreeNode root, Queue<TreeNode> queue) {
        if (root != null) {
            list.add(String.valueOf(root.val));
        } else {
            return;
        }
        if (root.left != null) {
            queue.add(root.left);
            list.add(String.valueOf(root.left.val));
        } else {
            list.add("#");
        }
        if (root.right != null) {
            queue.add(root.right);
            list.add(String.valueOf(root.right.val));
        } else {
            list.add("#");
        }
        while (!queue.isEmpty()) {
            TreeNode tn = queue.remove();
            if (tn.left != null) {
                queue.add(tn.left);
                list.add(String.valueOf(tn.left.val));
                if (tn.right == null) {
                    list.add("#");
                    continue;
                }
            } else {
                list.add("#");
            }
            if (tn.right != null) {
                queue.add(tn.right);
                list.add(String.valueOf(tn.right.val));
            } else {
                list.add("#");
            }
        }
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
        left = null;
        right = null;
    }
    @Override
    public String toString() {
        return "TreeNode [val=" + val + ", left=" + left + ", right=" + right + "]";
    }
}

Unique Binary Search Trees II

原文:http://blog.csdn.net/shijiebei2009/article/details/44566099

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!