1. 程式人生 > >LeetCode 95. Unique Binary Search Trees II(獨特的二進位制搜尋樹 II)

LeetCode 95. Unique Binary Search Trees II(獨特的二進位制搜尋樹 II)

原題

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

給定一個整數,生成所有結構上唯一的 BST (二進位制搜尋樹) 儲存值 1…n。

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Note:

Follow up: Recursive solution is trivial, could you do it iteratively?

題目: 給定一個二叉樹,返回其中序遍歷(注意中序遍歷的英寫法:inorder traversal

Reference Answer

思路分析

這道題目的做法和之前的unique BST略有不同,但主體思想是一致的。選定一個點作為根,依次產生可行的子樹,然後把解加到最後的解裡面。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
# self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n == 0: return [] return self.getTrees(1, n) def getTrees
(self, start, end): if start > end: return [None] solution = [] for rootval in range(start, end+1): left = self.getTrees(start, rootval-1) right = self.getTrees(rootval+1, end) for i in left: for j in right: root = TreeNode(rootval) root.left = i root.right = j solution.append(root) return solution

反思:

  1. 對於結果中的 [1,null,3,2] 中的 [null] 在程式碼中應該返回為 [None]