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

2021-10-07 13:01:23 字數 2377 閱讀 7127

#include

"bits/stdc++.h"

using

namespace std;

#define mem(a,b) memset(a,b,sizeof(a))

#define pb push_back

typedef

long

long ll;

const

int maxn =

1e4+7;

const

int inf = int_max;

const

int eps =10;

#define _debug

typedef

struct node* list;

typedef

struct node

;int n, h;

vector<

int>

preorder(9

),inorder(9

);list root =

newnode()

;unordered_map<

int,

int> mp;

bool ans =

false

;void

init()

for(

int i =

0; i < n; i++)}

void

display()

cout

"inorder list:"

int i =

0;i < n;i++

) cout<}list createt

(int pre_l,

int pre_r,

int in_l,

int in_r)

int pre_root = pre_l;

int in_root = mp[preorder[pre_root]];

list head =

newnode()

; head-

>data = preorder[pre_root]

;int len_left = in_root - in_l;

head-

>l =

createt

(pre_l +

1,pre_l + len_left, in_l, in_root -1)

; head-

>r =

createt

(pre_l +

1+ len_left, pre_r, in_root +

1, in_r)

;return head;

}void

printt

(list root)

d ++

; cout

(list root)

return1+

max(

dfs(root-

>l)

,dfs

(root-

>r));

}bool

judge

(list root)

int lh =

dfs(root-

>l)

;int rh =

dfs(root-

>r);if

(abs

(lh - rh)

>1)

return

(judge

(root-

>l)

&&judge

(root-

>r));

}int

main()

else

return0;

}

2、在判斷是否是平衡二叉樹過程中,遞迴計算樹高

後序遍歷的思想,通過引用,記錄樹高,後序遍歷因為先遍歷了左子樹和右子樹,同時也知道了左右子樹的高度deep_l, deep_r,所以可以得到此根節點的樹高 1 + max(deep_l, deep_r)。

bool

check

(list root,

int&deepth)

int deep_l, deep_r;

bool ans_l =

check

(root-

>l, deep_l)

;bool ans_r =

check

(root-

>r, deep_r);if

(ans_l && ans_r)

}return

false

;}

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

二叉樹的節點定義為 public class treenode 二叉樹的深度 根節點到葉節點的最長路徑長度 平衡二叉樹 二叉樹中任一節點的左右子樹的深度相差不超過1 遞迴的方法 如下 public boolean isbalanced treenode root intleft getheight ...

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

平衡二叉搜尋樹 balanced binary tree 具有以下性質 它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。思路 如果一顆二叉樹的所有子樹都是平衡二叉樹,它一定是平衡二叉樹。include using namespace std typedef...

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

平衡樹 balance tree,bt 指的是,任意節點的子樹的高度差都小於等於1。力扣 110也有該題,可以用來驗證。如果二叉樹為空,返回true。計算出左子樹和右子樹的最大深度。如果左右子樹的最大深度的差值小於2,並且左 右子樹都是平衡二叉樹,則該二叉樹是平衡二叉樹。判斷二叉樹是否是平衡二叉樹 ...