Unique Binary Search Trees II

本文详细介绍了如何使用递归方法生成所有可能的结构独特的二叉搜索树,包括实例演示和层次遍历验证。

问题来源: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 + "]";
    }
}
### 如何使用二叉搜索树(BST)实现 A+B 操作 在 C 编程语言中,可以通过构建两个二叉搜索树(BST),分别表示集合 A 和 B 的元素,然后通过遍历其中一个 BST 并将其节点插入到另一个 BST 中来完成 A+B 操作。以下是详细的实现方法: #### 数据结构定义 首先需要定义一个简单的二叉搜索树节点的数据结构。 ```c typedef struct TreeNode { int value; struct TreeNode* left; struct TreeNode* right; } TreeNode; ``` #### 插入函数 为了向 BST 添加新元素,可以编写如下 `insert` 函数。 ```c TreeNode* createNode(int value) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->value = value; newNode->left = NULL; newNode->right = NULL; return newNode; } void insert(TreeNode** root, int value) { if (*root == NULL) { *root = createNode(value); } else { if (value < (*root)->value) { insert(&((*root)->left), value); // Insert into the left subtree. } else if (value > (*root)->value) { insert(&((*root)->right), value); // Insert into the right subtree. } // If value == (*root)->value, do nothing since duplicates are not allowed in a set. } } ``` #### 合并操作 要执行 A+B 操作,即合并两棵 BST,可以从一棵树中提取所有元素并将它们逐个插入另一棵树中。 ```c // In-order traversal to extract elements from one tree and add them to another. void mergeTrees(TreeNode* sourceRoot, TreeNode** targetRoot) { if (sourceRoot != NULL) { mergeTrees(sourceRoot->left, targetRoot); // Traverse left subtree first. insert(targetRoot, sourceRoot->value); // Add current node's value to target tree. mergeTrees(sourceRoot->right, targetRoot); // Then traverse right subtree. } } ``` #### 主程序逻辑 假设我们已经初始化了两棵 BST 表示集合 A 和 B,则可以通过调用上述函数完成 A+B 操作。 ```c int main() { TreeNode* treeA = NULL; TreeNode* treeB = NULL; // Example: Adding values to Tree A. int arrayA[] = {5, 3, 7, 2, 4}; for (size_t i = 0; i < sizeof(arrayA)/sizeof(arrayA[0]); ++i) { insert(&treeA, arrayA[i]); } // Example: Adding values to Tree B. int arrayB[] = {6, 8, 1}; for (size_t i = 0; i < sizeof(arrayB)/sizeof(arrayB[0]); ++i) { insert(&treeB, arrayB[i]); } // Perform A + B by merging all nodes of treeB into treeA. mergeTrees(treeB, &treeA); // Now treeA contains all unique elements from both sets. return 0; } ``` 此代码片段展示了如何利用二叉搜索树的性质高效地进行集合并集运算[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值