3, binary tree

#二叉树的中序遍历
#速度可以,但是内存太大,需要优化
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        stack = []
        if root.left is not None:
            stack += self.inorderTraversal(root.left)
        stack.append(root.val)
        if root.right is not None:
            stack += self.inorderTraversal(root.right)
        return stack

Method a: recursion
is first counts the number of binary tree needs to be built. The number of possible binary search Cattleya prime number is a number.

We follow the logic above, but this time is to build a specific tree, rather than count.

algorithm

We removed the sequence numbers 1 ... n i, as the root of the current tree. Thus, the remaining i - 1 elements may be used to the left subtree, n - i elements for the right subtree.
As previously described, this will produce G (i - 1) and the kind of the left subtree G (n - i) seed right subtree, wherein G is the number of Cattleya.

Now, we have a sequence of 1 ... i - 1 The above procedure was repeated to construct all of the left subtree; Then i + 1 ... n repeated to build all right subtree.

In this way, we have roots and may i left subtree, right subtree list.

The last step of the cycle two lists, connect the left and right sub-tree sub-tree at the root.

Author: LeetCode
link: https: //leetcode-cn.com/problems/unique-binary-search-trees-ii/solution/bu-tong-de-er-cha-sou-suo-shu-ii-by-leetcode /
source: stay button (LeetCode)
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Published 35 original articles · won praise 10 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34358193/article/details/102654299