面试题 04.09. 二叉搜索树序列

从左向右遍历一个数组,通过不断将其中的元素插入树中可以逐步地生成一棵二叉搜索树。给定一个由不同节点组成的二叉搜索树,输出所有可能生成此树的数组。

 示例:
给定如下二叉树

        2
       / 
      1   3

返回:

[
   [2,1,3],
   [2,3,1]
]

大佬写的。未仔细研究:)

搜索

使用一个queue存储下个所有可能的节点
然后选择其中一个作为path的下一个元素
递归直到queue元素为空
将对应的path加入结果中
由于二叉搜索树没有重复元素, 而且每次递归的使用元素的顺序都不一样, 所以自动做到了去重
class Solution {

    List<List<Integer>> res = new LinkedList<>();

    public List<List<Integer>> BSTSequences(TreeNode root) {
        if (root == null) {
            res.add(new LinkedList<>());
            return res;
        }

        LinkedList<Integer> path = new LinkedList<>();
        path.add(root.val);

        helper(root, new LinkedList<>(), path);

        return res;
    }

    public void helper(TreeNode root, LinkedList<TreeNode> queue, LinkedList<Integer> path){
        if (root == null) return;

        if (root.left != null) queue.add(root.left);
        if (root.right != null) queue.add(root.right);

        if (queue.isEmpty()) {
            res.add(new LinkedList<>(path));
            return;
        }

        int lens = queue.size();
        for (int i = 0; i < lens; i++){
            TreeNode cur = queue.get(i);
            queue.remove(i);         
            path.add(cur.val);

            helper(cur, new LinkedList<>(queue), path);

            queue.add(i, cur);
            path.removeLast();
        }
    }
}
原文地址:https://www.cnblogs.com/kpwong/p/14716550.html