求乙個二叉樹中任意兩個節點間的距離,

2021-08-25 12:32:32 字數 1545 閱讀 3964

網易有道筆試:

(1).

求乙個二叉樹中任意兩個節點間的距離,

兩個節點的距離的定義是 這兩個節點間邊的個數,

比如某個孩子節點和父節點間的距離是1,和相鄰兄弟節點間的距離是2,優化時間空間複雜度。

c# codes as below:

using

system;

namespace ;

node

i2 = new

node

() ;

node

i3 = new

node

() ;

node

i4 = new

node

() ;

node

i5 = new

node

() ;

node

i6 = new

node

() ;

node

i7 = new

node

() ;

tree

tree = new

tree

() ;

int distance = new

helper().getdistance(tree, i4, i1);

console.writeline(distance);

console.readline(); }

} class

helper

public

int countdistance(int i, int j)

int distance = 0;

if (i != j)

return distance; }

public

int findnode(node

nodes, node

node)

return -1; }

private

void addnodes(node

nodes, node

node, int currentindex = 0)

if (node.right != null)

} public

int countmaxdepth(tree

tree) ;

tree

righttree = new

tree

() ;

int leftmaxlevel = countmaxdepth(lefttree);

int rightmaxlevel = countmaxdepth(righttree);

return leftmaxlevel > rightmaxlevel ? leftmaxlevel + 1 : rightmaxlevel + 1; }

} class

tree

} class

node

public

node

right

public t value }

}

二叉樹中任意兩個節點間的距離 原始碼

include include templatestruct bnode void visit t data bnode left bnode right 獲取訪問路徑 templatestd list getpath bnode root,bnode node iter iter left whi...

求二叉樹中任意兩個結點間的路徑(C )

include include using namespace std struct node void getnodepath node root,node node,vector v,bool flag 用後根遍歷的方式尋找node,找到後儲存從該節點到根節點的路徑 node creattree...

二叉樹兩個節點間的距離

距離是指連線兩個節點需要的最小的邊的條數。1找到節點的共同祖先 2 找到節點到共同祖先的距離dist,可以想到這個距離disthelper 節點到root距離 root到共同祖先的距離 3 兩個節點間距離 節點1到共同祖先的距離dist1 節點2到共同祖先的距離dist2 節點1到root距離 ro...