18 二叉樹查詢指定節點

2021-10-07 06:45:11 字數 2169 閱讀 8471

通過前序遍歷中序遍歷後序遍歷在二叉樹中查詢符合條件的節點。

**實現

public

class

binarytreedemo

}/**

* 定義二叉樹

*/class

binarytree

// 前序遍歷

public

void

preorder()

else

}// 中序遍歷

public

void

infixorder()

else

}// 後序遍歷

public

void

postorder()

else

}// 前序查詢節點

public

void

preordersearch

(int id)

else

else}}

// 中序查詢節點

public

void

infixordersearch

(int id)

else

else}}

// 後序查詢節點

public

void

postordersearch

(int id)

else

else}}

}/**

* 定義節點類

*/class

node

public

intgetid()

public

void

setid

(int id)

public node getleft()

public

void

setleft

(node left)

public node getright()

public

void

setright

(node right)

@override

public string tostring()

';}// 前序遍歷

public

void

preorder()

if(this

.right != null)

}// 中序遍歷

public

void

infixorder()

system.out.

println

(this);

if(this

.right != null)

}// 後序遍歷

public

void

postorder()

if(this

.right != null)

system.out.

println

(this);

}// 前序查詢節點

public node preordersearch

(int id)

node res = null;if(

this

.left != null)

if(res != null)if(

this

.right != null)

return res;

}// 中序查詢節點

public node infixordersearch

(int id)

if(res != null)if(

this

.id == id)if(

this

.right != null)

return res;

}// 後序查詢節點

public node postordersearch

(int id)

if(res != null)if(

this

.right != null)

if(res != null)if(

this

.id == id)

return res;

}}

二叉樹刪除節點, 查詢二叉樹最大值節點

從根節點往下分別查詢左子樹和右子樹的最大節點,再比較左子樹,右子樹,根節點的大小得到結果,在得到左子樹和右子樹最大節點的過程相似,因此可以採用遞迴的 樹節點結構 public class treenode public class solution treenode left maxnode roo...

二叉樹之查詢錯誤節點

一棵二叉樹原本是搜尋二叉樹,但是其中有兩個節點調換了位置,使得這棵二叉樹不再是搜尋二叉樹,請找到這兩個錯誤節點並返回他們的值。保證二叉樹中結點的值各不相同。給定一棵樹的根結點,請返回兩個調換了位置的值,其中小的值在前。分析 可以進行中序遍歷,那麼數值就是公升序,所以如果產生一次降序,那麼第乙個錯誤節...

二叉樹 二叉查詢樹

構建二叉樹,判斷是否為二叉查詢樹,遞迴先序遍歷,非遞迴中序遍歷 include include include include using namespace std 二叉樹結點 struct treenode 鍊錶結點 struct listnode struct tempnodetempnode...