平衡二叉樹的判斷和優化

2021-10-03 13:54:19 字數 1621 閱讀 8311

1、二叉樹的最大高度

public

intmaxdepth

(treenode root)

int left =

maxdepth

(root.left)

;int right =

maxdepth

(root.right)

;return

1+math.

max(left,right)

;}

2、判斷一棵二叉樹是否為平衡二叉樹

平衡二叉樹:乙個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1

源**:

public

boolean

isbalanced

(treenode root)

int leftheight =

getheight

(root.left)

;int rightheight =

getheight

(root.right);if

(math.

abs(rightheight - leftheight)

>1)

return

isbalanced

(root.left)

&&isbalanced

(root.right);}

private

intgetheight

(treenode root)

return math.

max(

getheight

(root.left)

,getheight

(root.right))+1;}

這裡存在乙個效率問題,在判斷根結點的時候,左右子樹上每乙個結點的高度已經求解過,當再求子樹是否平衡的時候還需要再求一遍子樹每個結點是否平衡

n個結點最壞時間複雜度就是 o(n^2)

優化:在求解當前結點的高度時,一定會遞下去求子樹高度,既然每次求當前結點高度都會求到子樹的高度,那麼有沒有辦法在求當前結點的時候把子樹的平衡性直接判斷。

思路:

public

boolean

isbalanced

(treenode root)

private

intgetheight

(treenode root)

int leftheight =

getheight

(root.left);if

(leftheight ==-1

)int rightheight =

getheight

(root.right);if

(rightheight ==-1

)return math.

abs(leftheight - rightheight)

<2?

math.

max(leftheight, rightheight)+1

:-1;

}

判斷平衡二叉樹

演算法 樹 平衡二叉樹 平衡二叉樹的概念 左右節點的樹高之差小於1。1.計算節點的高。通過遞迴,求出左右子樹的高度,當前節點的高度,最大的那乙個 1。int getheight treenode root 2.通過遞迴的方法計算左子樹和右子樹的樹高之差是否有小於1的,有就直接返回false.publ...

判斷平衡二叉樹

package com.jsp.tree 判斷是否是平衡二叉樹 author jiangshipan 任何乙個節點 左子樹和右子數高度差小於1 以每乙個節點為頭的樹都是平衡的,則這個樹平衡 可能 1.左樹不平 2.右樹不平 3.左或右高 整棵樹 public class isbalancedtree...

判斷平衡二叉樹

輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。最直接的做法,遍歷每個節點,借助乙個獲取樹深度的遞迴函式,根據該節點的左右子樹高度差判斷是否平衡,然後遞迴地對左右子樹進行判斷 pubic class solution private intmaxdepth treenode root 這種做法有很明顯...