判斷二叉樹是否為平衡二叉樹

2021-07-25 11:47:42 字數 909 閱讀 8937

一、線性思維

遍歷每個節點都時候,求左右子樹的深度,如果左右子樹深度相差不超過1,繼續遞迴遍歷左右節點,此種方法會重複遍歷,時間效率不高

is_balanced(t)

if t is null

return true;

left = treedepth(t.left);

right = treedepth(t.right);

diff = left - right;

if diff > 1 or diff < -1

return false;

return is_balanced(t.left) and is_balanced(t.right);

二、帶快取的遍歷

is_balanced(t, *depth)

if t is null

depth = 0;

return true;

if is_balanced(t.left, left) and is_balanced(t.right, right)

diff = left - right;

if diff <= 1 and diff >= -1

depth = 1 + ( left > right ? left : right );

return true;

return false;

**三、時間複雜度o(n),這種比較好理解

/**

* definition for a binary tree node.

* struct treenode ;

*/ int dfsheight(struct treenode* root)

bool isbalanced(struct treenode* root)

判斷二叉樹是否為平衡二叉樹

題目 平衡二叉樹的性質為 要麼是一棵空樹,要麼任何乙個節點的左右子樹高度差的絕對值不超過1。給定一棵二叉樹的頭結點head,判斷這棵二叉樹是否為平衡二叉樹。要求 如果二叉樹的節點數為n,要求時間複雜度為o n 判斷二叉樹是否為二叉樹 public boolean isbalance node hea...

判斷二叉樹是否為平衡二叉樹

要判斷二叉樹是否為平衡二叉樹 平衡二叉樹的定義 在乙個二叉樹中 每個節點子樹的左右高度差不超過1 1 首先判斷它的根節點是否為空 若是的話,就是平衡二叉樹 2 分別求出左右子樹的高度 若高度的絕對值不超過一則為平衡二叉樹 計算二叉樹高度 public static int calchigh node...

判斷二叉樹是否為平衡二叉樹

給定一棵樹,判斷是否為平衡二叉樹 逐層根據高度判斷是否平衡 def is balance1 self def height node if node is none return 0 l height node.left r height node.right return max l,r 1 de...