222 完全二叉樹的節點個數

2022-05-08 22:24:13 字數 1864 閱讀 1346

給出乙個完全二叉樹,求出該樹的節點個數。

說明:完全二叉樹的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第 h 層,則該層包含 1~ 2h 個節點。

示例:輸入:1/

2 3

/ \ /

4 5 6

輸出: 6

1.土方法:

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def countnodes(self, root: treenode) -> int:

_maxdepth,final_cnt=0,0

flag=1

def dfs(node,curdepth):

nonlocal _maxdepth,final_cnt,flag

if not flag or not node:

return

_maxdepth=max(_maxdepth,curdepth)

if node and not node.left and not node.right and curdepth==_maxdepth:

final_cnt+=1

return

if node and not node.left and not node.right and curdepth==_maxdepth-1:

flag=0

return

if node.left:

dfs(node.left,curdepth+1)

if node.right:

dfs(node.right,curdepth+1)

dfs(root,0)

return 2**_maxdepth-1+final_cnt

2.不那麼土的:

#

## [222] 完全二叉樹的節點個數

## definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def countnodes(self, root: treenode) -> int:

def depth(node):

depth=0

while node and node.left:

node=node.left

depth+=1

return depth

if not root:

return 0

le=depth(root.left)

ri=depth(root.right)

if le==ri and root.left:

return (1<<(le+1))+self.countnodes(root.right)

elif root.right:

return (1<<(ri+1))+self.countnodes(root.left)

return 1

222 完全二叉樹的節點個數

要求複雜度小於o n 一提到複雜度小於o n 就應該想到二分法。一開始想到的是對倒數第二行用二分法,但是要儲存倒數第二行的結點需要層次遍歷,複雜度是o n 所以就要從根結點開始每一層都用一次二分法,複雜度就是o d 2 o logn 2 每一層的二分法的目的是找到最後一層的最後乙個結點在目前這個結點...

222 完全二叉樹的節點個數

給出乙個完全二叉樹,求出該樹的節點個數。說明 完全二叉樹的定義如下 在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第 h 層,則該層包含 1 2h 個節點。示例 輸入 1 2 3 4 5 6 輸出 6 defini...

222 完全二叉樹的節點個數

1.使用遞迴來實現 class solution 2.根據完全二叉樹的性質簡化遍歷次數 功能 判斷最後一層第index個索引是否存在 root 二叉樹根節點 index 判斷最後一層索引為index的節點是否存在,索引範圍是 1,2 depth depth 倒數第二層的深度,這是因為滿二叉樹最後一層...