create ancestor matrix for binary tree

前端 未结 1 1467
别跟我提以往
别跟我提以往 2021-02-11 09:23
     1
   /  \\
  2    3
 / \\   / \\
4   5 6   7

for the given binary tree we need to create a matrix a[7][7] satisfying the ancestor property like

相关标签:
1条回答
  • 2021-02-11 09:49

    temp contains the path from root to current node, i.e. the set of nodes visited while walking down the tree to arrive at the current node.

    If you have a parent pointer in each node (but I guess not), you can follow those pointers and walk up the tree to traverse the same set of nodes as temp. But this uses more memory.

    You can also walk down the tree several times (pseudocode):

    def updatematrix(a,node):
      if node is null: return
      walkDown(a.data,node.left)
      walkDown(a.data,node.right)
      updatematrix(a,node.left)
      updatematrix(a,node.right)
    
    def walkDown(data,node):
      if node is null: return
      a[node][data] = 1
      walkDown(data,node.left)
      walkDown(data,node.right)
    

    Same complexity, but the pattern of memory access looks less cache friendly.

    0 讨论(0)
提交回复
热议问题