Given a BST and its root, print all sequences of nodes which give rise to the same bst

前端 未结 8 981
半阙折子戏
半阙折子戏 2020-12-13 05:49

Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

  3
 /  \\
1             


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 06:09

    
    public class Solution {
        ArrayList> result;
        /*Return the children of a node */
        ArrayList getChilden(TreeNode parent) {
            ArrayList child = new ArrayList();
            if(parent.left != null) child.add(parent.left);
            if(parent.right != null) child.add(parent.right);
            return child;
        }
        /*Gets all the possible Compinations*/
        void getPermutations(ArrayList permutations, LinkedList current) {
            if(permutations.size() == 0) {
                result.add(current);
                return;
            }
            int length = permutations.size();
            for(int i = 0; i < length; i++) {
                TreeNode node = permutations.get(i);
                permutations.remove(i);
                ArrayList newPossibilities = new ArrayList();
                newPossibilities.addAll(permutations);
                newPossibilities.addAll(getChilden(node));
                LinkedList newCur = new LinkedList();
                newCur.addAll(current);
                newCur.add(node.val);
                getPermutations(newPossibilities, newCur);
                permutations.add(i,node);
            }
        }
    
        /*This method returns a array of arrays which will lead to a given BST*/
        ArrayList> inputSequencesForBst(TreeNode node) { 
            result = new ArrayList>();
            if(node == null)
                return result;
            ArrayList permutations = getChilden(node);
            LinkedList current = new LinkedList();
            current.add(node.val);
            getPermutations(permutations, current);
            return result;
        }
    }
    

    My solution. Works perfectly.

提交回复
热议问题