面试题 04.09. 二叉搜索树序列-----回溯法

题目表述

从左向右遍历一个数组,通过不断将其中的元素插入树中可以逐步地生成一棵二叉搜索树。

给定一个由不同节点组成的二叉搜索树 root,输出所有可能生成此树的数组。

示例:

输入: root = [2,1,3]
**输出: **[[2,1,3],[2,3,1]]
**解释: **数组 [2,1,3]、[2,3,1] 均可以通过从左向右遍历元素插入树中形成以下二叉搜索树

2
  / \
  1 3

回溯法

  • 遍历数组,将元素逐个插入树中生成二叉搜索树的过程,可以反过来看成是遍历二叉搜索树的过程。每个节点只能前往它的左右子节点,不能直接到达孙子节点,且一棵树的根节点总是先于它的左右子树被插入到树中;

  • 用一个双端队列deque来存储这次可以插入的候选节点,当队列中没有候选节点时,视为一种方案,存入结果数组中;

  • 从队首取出,从队尾插入。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    Deque<Integer> path = new LinkedList<>();
    public List<List<Integer>> BSTSequences(TreeNode root) {
        List<TreeNode> que = new LinkedList<>();
        if(root != null){
            que.add(root);
        }
        dfs(que);
        return res;
    }
    public void dfs(List<TreeNode> que){
        if(que.isEmpty()){
            res.add(new ArrayList<>(path));
            return;
        }
        List<TreeNode> copy = new LinkedList<>(que);
        for(int i = 0; i < que.size();i++){
            TreeNode tmp = que.get(i);
            path.addLast(tmp.val);
            que.remove(i);
            if(tmp.left != null) que.add(tmp.left);
            if(tmp.right != null) que.add(tmp.right);
            dfs(que);
            path.removeLast();
            que = new LinkedList<>(copy);
        }
    }

}
posted @ 2022-05-16 23:22  YoungerWb  阅读(66)  评论(0)    收藏  举报