Пример #1
0
def build(data):
    if len(data) == 0:
        return TreeNode(0)
    nodeQueue = []
    # 创建一根节点,并将根节点进栈
    root = TreeNode(data[0])
    nodeQueue.append(root)
    # 记录当前行节点的数量
    lineNum = 2
    # 记录当前行中数字在数组中的位置
    startIndex = 1
    # 记录数组中剩余元素的数量
    restLength = len(data) - 1
    while restLength > 0:
        for index in range(startIndex, startIndex + lineNum, 2):
            if index == len(data):
                return root
            cur_node = nodeQueue.pop()
            if data[index] is not None:
                cur_node.left = TreeNode(data[index])
                nodeQueue.append(cur_node.left)
            if index + 1 == len(data):
                return root
            if data[index + 1] is not None:
                cur_node.right = TreeNode(data[index + 1])
                nodeQueue.append(cur_node.right)
        startIndex += lineNum
        restLength -= lineNum
        # 此处用来更新下一层树对应节点的最大值
        lineNum = len(nodeQueue) * 2
    return root
def stringToTreeNode(input):
    input = input.strip()
    input = input[1:-1]
    if not input:
        return None

    inputValues = [s.strip() for s in input.split(',')]
    root = TreeNode(int(inputValues[0]))
    nodeQueue = [root]
    front = 0
    index = 1
    while index < len(inputValues):
        node = nodeQueue[front]
        front = front + 1

        item = inputValues[index]
        index = index + 1
        if item != "null":
            leftNumber = int(item)
            node.left = TreeNode(leftNumber)
            nodeQueue.append(node.left)

        if index >= len(inputValues):
            break

        item = inputValues[index]
        index = index + 1
        if item != "null":
            rightNumber = int(item)
            node.right = TreeNode(rightNumber)
            nodeQueue.append(node.right)
    return root
Пример #3
0
 def pruneTree(self, root: TreeNode) -> TreeNode:
     if root:
         root.left = self.pruneTree(root.left)
         root.right = self.pruneTree(root.right)
         if root.val == 0 and not root.left and not root.right:
             return None
     return root
Пример #4
0
 def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
     if root:
         root.left = self.removeLeafNodes(root.left, target)
         root.right = self.removeLeafNodes(root.right, target)
         if root.val == target and not root.left and not root.right:
             root = None
     return root
Пример #5
0
 def reConstructBinaryTree(self, pre, tin):
     if not pre or not tin:
         return None
     root = TreeNode(pre.pop(0))
     index = tin.index(root.val)
     root.left = self.reConstructBinaryTree(pre, tin[:index])
     root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
     return root
Пример #6
0
def StackBrowser(root, flist=None, tb=None, top=None):
    if top is None:
        top = tk.Toplevel(root)
    sc = ScrolledCanvas(top, bg="white", highlightthickness=0)
    sc.frame.pack(expand=1, fill="both")
    item = StackTreeItem(flist, tb)
    node = TreeNode(sc.canvas, None, item)
    node.expand()
Пример #7
0
def StackBrowser(root, flist=None, tb=None, top=None):
    if top is None:
        top = tk.Toplevel(root)
    sc = ScrolledCanvas(top, bg="white", highlightthickness=0)
    sc.frame.pack(expand=1, fill="both")
    item = StackTreeItem(flist, tb)
    node = TreeNode(sc.canvas, None, item)
    node.expand()
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
    if not preorder:
        return None
    root = TreeNode(preorder[0])
    i = inorder.index(root.val)
    root.left = self.buildTree(preorder[1:i+1], inorder[:i])
    root.right = self.buildTree(preorder[i+1:], inorder[i+1:])
    return root
Пример #9
0
 def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
     if t1 is None:
         return t2
     if t2 is None:
         return t1
     t1.val += t2.val
     t1.left = self.mergeTrees(t1.left, t2.left)
     t1.right = self.mergeTrees(t1.right, t2.right)
     return t1
Пример #10
0
def buildTree(self, data, pos):
    pos += 1
    if pos >= len(data) or data[pos] == None:
        return None, pos

    root = TreeNode(data[pos])
    root.left, pos = self.buildTree(data, pos)
    root.right, pos = self.buildTree(data, pos)
    return root, pos
Пример #11
0
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if inorder:
            index = inorder.index(preorder.pop(0))

            node = TreeNode(inorder[index])
            node.left = self.buildTree(preorder, inorder[0:index])
            node.right = self.buildTree(preorder, inorder[index + 1:])

            return node
Пример #12
0
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
    if not inorder:
        return None

    root = TreeNode(postorder[-1])
    i = inorder.index(root.val)
    root.left = self.buildTree(inorder[:i], postorder[:i])
    root.right = self.buildTree(inorder[i+1:], postorder[i:-1])

    return root
Пример #13
0
    def sortedArrayToBST(self, num):
        if not num:
            return None

        mid = len(num) // 2

        root = TreeNode(num[mid])
        root.left = self.sortedArrayToBST(num[:mid])
        root.right = self.sortedArrayToBST(num[mid + 1:])

        return root
 def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
     if not nums:
         return None
     mid = len(nums) // 2
     root = TreeNode(nums[mid])
     left = nums[:mid]
     right = nums[mid + 1:]
     if left:
         root.left = self.sortedArrayToBST(left)
     if right:
         root.right = self.sortedArrayToBST(right)
     return root
Пример #15
0
def _object_browser(parent):
    import sys
    from tkinter import Toplevel
    top = Toplevel(parent)
    top.title('Test debug object browser')
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry('+%d+%d' % (x + 100, y + 175))
    top.configure(bd=0, bg='yellow')
    top.focus_set()
    sc = ScrolledCanvas(top, bg='white', highlightthickness=0, takefocus=1)
    sc.frame.pack(expand=1, fill='both')
    item = make_objecttreeitem('sys', sys)
    node = TreeNode(sc.canvas, None, item)
    node.update()
Пример #16
0
def _object_browser(parent):  # htest #
    import sys
    from tkinter import Toplevel
    top = Toplevel(parent)
    top.title("Test debug object browser")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("+%d+%d" % (x + 100, y + 175))
    top.configure(bd=0, bg="yellow")
    top.focus_set()
    sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
    sc.frame.pack(expand=1, fill="both")
    item = make_objecttreeitem("sys", sys)
    node = TreeNode(sc.canvas, None, item)
    node.update()
Пример #17
0
def _object_browser(parent):  # htest #
    import sys
    from tkinter import Toplevel
    top = Toplevel(parent)
    top.title("Test debug object browser")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    top.geometry("+%d+%d"%(x + 100, y + 175))
    top.configure(bd=0, bg="yellow")
    top.focus_set()
    sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
    sc.frame.pack(expand=1, fill="both")
    item = make_objecttreeitem("sys", sys)
    node = TreeNode(sc.canvas, None, item)
    node.update()
Пример #18
0
 def remote_stack_viewer(self):
     from idlelib import debugobj_r
     oid = self.rpcclt.remotequeue('exec', 'stackviewer', ('flist', ), {})
     if oid is None:
         self.tkconsole.root.bell()
         return
     item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid)
     from idlelib.tree import ScrolledCanvas, TreeNode
     top = Toplevel(self.tkconsole.root)
     theme = idleConf.CurrentTheme()
     background = idleConf.GetHighlight(theme, 'normal')['background']
     sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
     sc.frame.pack(expand=1, fill='both')
     node = TreeNode(sc.canvas, None, item)
     node.expand()
Пример #19
0
def _object_browser(parent):
    import sys
    from tkinter import Tk
    root = Tk()
    root.title("Test debug object browser")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    root.configure(bd=0, bg="yellow")
    root.focus_set()
    sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
    sc.frame.pack(expand=1, fill="both")
    item = make_objecttreeitem("sys", sys)
    node = TreeNode(sc.canvas, None, item)
    node.update()
    root.mainloop()
Пример #20
0
 def init(self, flist):
     self.flist = flist
     # reset pyclbr
     pyclbr._modules.clear()
     # create top
     self.top = top = ListedToplevel(flist.root)
     top.protocol("WM_DELETE_WINDOW", self.close)
     top.bind("<Escape>", self.close)
     if self._htest:  # place dialog below parent if running htest
         top.geometry(
             "+%d+%d" %
             (flist.root.winfo_rootx(), flist.root.winfo_rooty() + 200))
     self.settitle()
     top.focus_set()
     # create scrolled canvas
     theme = idleConf.CurrentTheme()
     background = idleConf.GetHighlight(theme, 'normal')['background']
     sc = ScrolledCanvas(top,
                         bg=background,
                         highlightthickness=0,
                         takefocus=1)
     sc.frame.pack(expand=1, fill="both")
     item = self.rootnode()
     self.node = node = TreeNode(sc.canvas, None, item)
     node.update()
     node.expand()
Пример #21
0
    def init(self):
        "Create browser tkinter widgets, including the tree."
        global file_open
        root = self.master
        flist = (pyshell.flist if not (self._htest or self._utest) else
                 pyshell.PyShellFileList(root))
        file_open = flist.open
        pyclbr._modules.clear()

        # create top
        self.top = top = ListedToplevel(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", self.close)
        if self._htest:  # place dialog below parent if running htest
            top.geometry("+%d+%d" %
                         (root.winfo_rootx(), root.winfo_rooty() + 200))
        self.settitle()
        top.focus_set()

        # create scrolled canvas
        theme = idleConf.CurrentTheme()
        background = idleConf.GetHighlight(theme, 'normal')['background']
        sc = ScrolledCanvas(top,
                            bg=background,
                            highlightthickness=0,
                            takefocus=1)
        sc.frame.pack(expand=1, fill="both")
        item = self.rootnode()
        self.node = node = TreeNode(sc.canvas, None, item)
        if not self._utest:
            node.update()
            node.expand()
Пример #22
0
 def createtreemap(self,
                   tmrootnode=None,
                   sizepropname=SIZE_PROP,
                   clrpropname=CLR_PROP):
     del self.filetree
     if (tmrootnode != None):
         self.tmrootnode = tmrootnode
     ftreeroot = FileTreeItem(self.tmrootnode, self.tmcanvas)
     self.filetree = TreeNode(self.treecanvas, None, ftreeroot)
     self.filetree.update()
     self.filetree.expand()
     clrmap = self.getPropClrMap(self.tmrootnode, clrpropname)
     self.tmcanvas.set(tmcolormap=clrmap,
                       sizeprop=sizepropname,
                       clrprop=clrpropname,
                       upper=[1200, 700],
                       tooltip=self.tooltip)
     self.tmcanvas.drawTreemap(self.tmrootnode)
        def helper(in_left, in_right):
            # if there is no elements to construct subtrees
            if in_left > in_right:
                return None

            # pick up the last element as a root
            val = postorder.pop()
            root = TreeNode(val)

            # root splits inorder list
            # into left and right subtrees
            index = idx_map[val]

            # build right subtree
            root.right = helper(index + 1, in_right)
            # build left subtree
            root.left = helper(in_left, index - 1)
            return root
        def helper(in_left=0, in_right=len(inorder)):
            nonlocal pre_idx
            # if there is no elements to construct subtrees
            if in_left == in_right:
                return None

            # pick up pre_idx element as a root
            root_val = preorder[pre_idx]
            root = TreeNode(root_val)

            # root splits inorder list
            # into left and right subtrees
            index = idx_map[root_val]

            # recursion
            pre_idx += 1
            # build left subtree
            root.left = helper(in_left, index)
            # build right subtree
            root.right = helper(index + 1, in_right)
            return root
Пример #25
0
 def init(self, flist):
     self.flist = flist
     pyclbr._modules.clear()
     self.top = top = ListedToplevel(flist.root)
     top.protocol('WM_DELETE_WINDOW', self.close)
     top.bind('<Escape>', self.close)
     if self._htest:
         top.geometry(
             '+%d+%d' %
             (flist.root.winfo_rootx(), flist.root.winfo_rooty() + 200))
     self.settitle()
     top.focus_set()
     theme = idleConf.CurrentTheme()
     background = idleConf.GetHighlight(theme, 'normal')['background']
     sc = ScrolledCanvas(top,
                         bg=background,
                         highlightthickness=0,
                         takefocus=1)
     sc.frame.pack(expand=1, fill='both')
     item = self.rootnode()
     self.node = node = TreeNode(sc.canvas, None, item)
     node.update()
     node.expand()
Пример #26
0
    def Parent__Dir(self):
        Parent__Directory = self.home
        to__ParentDir = FileTreeItem(self.home)

        home__node = TreeNode(self.SC.canvas, to__ParentDir)
        home__node.expand()
Пример #27
0
class App(object):
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("Source Monitor Treemap")
        self.initMenu()
        self.initDropDown()
        self.pane = tkinter.PanedWindow(self.root, orient=tkinter.HORIZONTAL)
        self.pane.pack(fill=tkinter.BOTH, expand=1)
        self.initTreeCanvas()
        self.initTreemapCanvas()
        self.filetree = None

    def initTreemapCanvas(self):
        self.tmcanvas = TreemapSquarified(self.pane, width='13i', height='8i')
        self.tmcanvas.config(bg='white')
        self.pane.config(bg='blue')
        self.pane.add(self.tmcanvas.frame)
        self.pane.paneconfigure(self.tmcanvas.frame,
                                sticky=tkinter.N + tkinter.S + tkinter.E +
                                tkinter.W)
        self.tooltip = TkCanvasToolTip(self.tmcanvas, follow=True)

    def initTreeCanvas(self):
        frame = tkinter.Frame(self.pane)
        self.treecanvas = createScrollableCanvas(frame, width='2i')
        self.pane.add(frame)
        self.pane.paneconfigure(frame,
                                sticky=tkinter.N + tkinter.S + tkinter.E +
                                tkinter.W)

    def initMenu(self):
        menubar = tkinter.Menu(self.root)
        filemenu = tkinter.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.openSMFile)
        filemenu.add_command(label="Exit", command=self.root.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        self.root.config(menu=menubar)

    def initDropDown(self):
        self.dropdownframe = tkinter.Frame(self.root)
        self.sizeOption = tkinter.StringVar()
        self.sizeOption.set(SIZE_PROP)
        self.colorOption = tkinter.StringVar()
        self.colorOption.set(CLR_PROP)
        # get the list of options
        options = set(SMPROP_MAPPING.itervalues())
        # now convert the set to sorted list
        options = sorted(options)

        self.optionsSize = tkinter.OptionMenu(self.dropdownframe,
                                              self.sizeOption,
                                              command=self.optionchange,
                                              *options)
        self.optionsSize.grid(row=0, column=0)
        self.optionsClr = tkinter.OptionMenu(self.dropdownframe,
                                             self.colorOption,
                                             command=self.optionchange,
                                             *options)
        self.optionsClr.grid(row=0, column=1)
        self.dropdownframe.pack()

    def optionchange(self, param):
        sizepropname = self.sizeOption.get()
        clrpropname = self.colorOption.get()
        self.createtreemap(sizepropname=sizepropname, clrpropname=clrpropname)

    def createtreemap(self,
                      tmrootnode=None,
                      sizepropname=SIZE_PROP,
                      clrpropname=CLR_PROP):
        del self.filetree
        if (tmrootnode != None):
            self.tmrootnode = tmrootnode
        ftreeroot = FileTreeItem(self.tmrootnode, self.tmcanvas)
        self.filetree = TreeNode(self.treecanvas, None, ftreeroot)
        self.filetree.update()
        self.filetree.expand()
        clrmap = self.getPropClrMap(self.tmrootnode, clrpropname)
        self.tmcanvas.set(tmcolormap=clrmap,
                          sizeprop=sizepropname,
                          clrprop=clrpropname,
                          upper=[1200, 700],
                          tooltip=self.tooltip)
        self.tmcanvas.drawTreemap(self.tmrootnode)

    def getNeutralVal(self, clrpropname, minval, maxval):
        neutralval = COLOR_PROP_CONFIG.get(clrpropname)

        if (neutralval == None):
            neutralval = 0.5 * (minval + maxval)
        return (neutralval)

    def getPropClrMap(self, tmrootnode, clrpropname):
        clrmap = TMColorMap(minclr=(0, 255, 0), maxclr=(255, 0, 0))
        minval = tmrootnode.minclr(clrpropname)
        maxval = tmrootnode.maxclr(clrpropname)
        neutralval = self.getNeutralVal(clrpropname, minval, maxval)
        clrmap.setlimits(minval, maxval, neutralval=neutralval)
        return (clrmap)

    def openSMFile(self):
        filename = tkinter.filedialog.askopenfilename(
            title="Choose Source Monitor output file",
            filetypes=SMFILEFORMATS,
            defaultextension=".xml")
        smtree = SMTree(filename)
        self.createtreemap(smtree)

    def run(self):
        self.root.mainloop()
Пример #28
0
    def Find__Directpry(self):
        find__Dir = input('Enter Directory Path :: \n')
        locate__Dir = FileTreeItem(find__Dir)

        dirLocate__node = TreeNode(self.SC.canvas, None, locate__Dir)
        dirLocate__node.expand()
Пример #29
0
        # self.get_max_depth(root)
        # return self.result

    def get_max_depth(self, root):
        if root is None:
            return 0
        left = self.get_max_depth(root.left)
        right = self.get_max_depth(root.right)
        self.result = max(self.result, right + left)
        return max(left + 1, right + 1)


# Main Call
# Initialize the Tree First

tree_root = TreeNode(1)
tree_left_1 = TreeNode(2)
tree_right_1 = TreeNode(3)
tree_left_2 = TreeNode(4)
tree_left_3 = TreeNode(5)
tree_root.left = tree_left_1
tree_left_1.left = tree_left_2
tree_left_1.right = tree_left_3
tree_root.right = tree_right_1

tree_right_1.left = None
tree_right_1.right = None
tree_left_2.left = None
tree_left_2.right = None
tree_left_3.left = None
tree_left_3.right = None
Пример #30
0
def invertTree(root: TreeNode) -> TreeNode:
    if root:
        root.left, root.right = \
            invertTree(root.right), invertTree(root.left)
        return root
    return None
Пример #31
0
# from treenode import TreeNode
from idlelib.tree import TreeNode

a: TreeNode = TreeNode(1)
Пример #32
0
def invertTree(root: TreeNode):
    if root:
        root.left, root.right = \
            invertTree(root.right), invertTree(root.left)
        return root
    return None  # 사실 파이썬에선 이거 생략해도 오류를 안내지만, 좀더 정석적인 코드를 위해!