這個問題在這里已經有了答案: 在二叉搜索樹中查找高度 26 答案 10 小時前關閉。
我已經開始實作這段代碼,但現在我被困住了。我正在嘗試將樹的高度從根回傳到最遠的葉子。我可以訪問外部的葉子,但不能訪問內部的葉子。如何將內部葉子合并到我的函式中以回傳最高高度?
static int getHeight(Node root){
int left = 0;
int right = 0;
Node head = root;
while(root.left != null) {
root = root.left;
left ;
}
while(head.right != null) {
head = head.right;
right ;
}
return Math.Max(left, right);
uj5u.com熱心網友回復:
試試這個遞回演算法:
static int getHeight(Node root){
int left = 0;
int right = 0;
if(root==null) return 0
left = getHeight(root.left) 1;
right= getHeight(root.right) 1;
return Math.Max(left, right);
}
uj5u.com熱心網友回復:
例如,您可以嘗試B readth First Search ( BFS ) ,讓它成為非遞回方法(因為您想遍歷):
static int getHeight(Node root) {
if (root == null)
return 0;
Queue<Node> agenda = new Queue<Node>();
agenda.Enqueue(root);
int result = 0;
while (agenda.Count > 0) {
result = 1;
for (int i = agenda.Count - 1; i >= 0; --i) {
var node = agenda.Dequeue();
if (node.left != null)
agenda.Enqueue(node.left);
if (node.right != null)
agenda.Enqueue(node.right);
}
}
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498396.html
上一篇:如何允許可為空的布爾URI引數?
