演算法10 二叉樹

2021-08-30 15:32:19 字數 1795 閱讀 3809

1.給定二叉樹的前序和中序遍歷陣列,重新構建二叉樹

int pre = new int;

int in = new int;

假設前序陣列pre  起始座標ps,pe    中序陣列in   is,ie

前序陣列的第乙個元素即為根節點rootvalue = 1

尋找根節點在中序陣列中的位置索引rootinindex = 3

從中序陣列中可以發現左子樹的個數rootinindex-is=3

從前序陣列中確定左子樹的起始座標 ps+1, ps+rootinindex-is    右子樹的起始座標 ps+rootinindex-is+1,pe

中序陣列中左子樹座標  is,rootinindex-1   右子樹 rootinindex+1  ie

首先建立根節點,然後根據根節點位置,劃分左右子樹的陣列座標範圍,遞迴呼叫生成二叉樹。

public treenode reconstructbinarytree(int  pre,int  in) 	

public static treenode rebuildtree(int pre, int ps, int pe, int in, int is, int ie)

} //左子樹的節點個數rootinindex-is

//前序序列中左子樹的座標起始索引 ps+1,ps+rootinindex-is 右子樹的座標ps+rootinindex-is+1,pe

//中序序列中左子樹 is,rootinindex-1 右子樹 rootinindex+1,ie

treenode root = new treenode(rootvalue);

root.left = rebuildtree(pre, ps+1, ps+rootinindex-is, in, is, rootinindex-1);

root.right = rebuildtree(pre, ps+rootinindex-is+1, pe, in, rootinindex+1, ie);

return root;

}

看了一下大神的**改了一下:

public static treenode rebuildtree(int pre, int in)
用乙個map來儲存中序數列的數值與索引的對應關係,避免每次迴圈取值。

2.二叉樹的下乙個節點

給定二叉樹以及乙個節點    求出中序序列的下乙個節點。樹節點有指向父節點的指標。

分三種情況:

1.右子樹非空,下乙個節點是右子樹的最左節點

2.右子樹空  該節點是父節點的左節點  下乙個節點是其父節點

3.右子樹空,是其父節點的有右節點,則沿該節點向父節點回溯,比較父節點與其父節點的父節點的關係若為為左孩子說明該父節點的父節點為下乙個節點,若沒有這樣的節點,說明該節點為最後乙個節點,輸出null即可。

public static treenode getnexttreenodeinorder(treenode root, treenode target)

return tmp;

} treenode parent = target.parent;

if(parent != null && parent.left == target)

return parent;

while(parent != null && parent.left != target)

return parent;

}

啊哈!演算法 演算法10 二叉樹

二叉樹是一種特殊的樹。二叉樹的特點是每個結點最多有兩個兒子,左邊的叫做左兒子,右邊的叫做右兒子,或者說每個結點最多有兩棵子樹。更加嚴格的遞迴定義是 二叉樹要麼為空,要麼由根結點 左子樹和右子樹組成,而左子樹和右子樹分別是一棵二叉樹。下面這棵樹就是一棵二叉樹。二叉樹的使用範圍最廣,一棵多叉樹也可以轉化...

二叉樹演算法

include include include define elementtype int node structure constructor typedef struct bt binarytreenode,btroot function declear inorder btroot root...

二叉樹演算法

二叉樹的遍歷演算法 1.先序遍歷 對每乙個節點將其看作根節點按照根左右的順序進行遍歷。示例 void preordertree node root 先序遍歷二叉樹 return 2.中序遍歷 對每乙個節點將其看作根節點按照左根右的順序進行便利。示例 void inordertree node roo...