Iterating over a Binary Tree with O(1) Auxiliary Space

后端 未结 10 1263
广开言路
广开言路 2020-11-30 04:03

Is it possible to iterate over a binary tree in O(1) auxiliary space (w/o using a stack, queue, etc.), or has this been proven impossible? If it is possible, how can it be

10条回答
  •  一生所求
    2020-11-30 04:38

    Pointers from nodes to their ancestors can be had with no (well, two bits per node) additional storage using a structure called a threaded tree. In a threaded tree, null links are represented by a bit of state rather than a null pointer. Then, you can replace the null links with pointers to other nodes: left links point to the successor node in an inorder traversal, and right links to the predecessor. Here is a Unicode-heavy diagram (X represents a header node used to control the tree):

                                             ╭─┬────────────────────────────────────────╮
       ╭─────────────────────────▶┏━━━┯━━━┯━━▼┓│                                        │
       │                        ╭─╂─  │ X │  ─╂╯                                        │ 
       │                        ▼ ┗━━━┷━━━┷━━━┛                                         │
       │                    ┏━━━┯━━━┯━━━┓                                               │
       │               ╭────╂─  │ A │  ─╂──╮                                            │
       │               ▼    ┗━━━┷━━━┷━━━┛  │                                            │    
       │        ┏━━━┯━━━┯━━━┓    ▲         │        ┏━━━┯━━━┯━━━┓                       │
       │      ╭─╂─  │ B │  ─╂────┤         ├────────╂─  │ C │  ─╂───────╮               │
       │      ▼ ┗━━━┷━━━┷━━━┛    │         ▼        ┗━━━┷━━━┷━━━┛       ▼               │  
       │┏━━━┯━━━┯━━━┓ ▲          │   ┏━━━┯━━━┯━━━┓       ▲         ┏━━━┯━━━┯━━━┓        │
       ╰╂─  │ D │  ─╂─╯          ╰───╂   │ E │  ─╂╮      │        ╭╂─  │ F │  ─╂╮       │ 
        ┗━━━┷━━━┷━━━┛                ┗━━━┷━━━┷━━━┛▼      │        ▼┗━━━┷━━━┷━━━┛▼       │
                                        ▲ ┏━━━┯━━━┯━━━┓  │ ┏━━━┯━━━┯━━━┓ ▲ ┏━━━┯━━━┯━━━┓│
                                        ╰─╂─  │ G │   ╂──┴─╂─  │ H │  ─╂─┴─╂─  │ J │  ─╂╯
                                          ┗━━━┷━━━┷━━━┛    ┗━━━┷━━━┷━━━┛   ┗━━━┷━━━┷━━━┛
    
    

    Once you have the structure, doing an inorder traversal is very, very easy:

    Inorder-Successor(p)
        p points to a node.  This routine finds the successor of p in
        an inorder traversal and returns a pointer to that node
    
        qp.right
        If p.rtag = 0 Then
            While q.ltag = 0 Do
                qq.left
            End While
        End If
    
        Return q
        

    Lots more information on threaded trees can be found in Art of Computer Programming Ch.2 §3.1 or scattered around the Internet.

提交回复
热议问题