二叉樹後繼節點

2021-09-14 08:33:56 字數 2560 閱讀 8152

二叉樹後繼節點,中序遍歷的後乙個節點

(1)有右子樹,右子樹的最左節點是後繼

(2)無右子樹,並且是父節點的左孩子,父節點為後繼

(3)無右子樹,並且是父節點的右孩子,查該節點是哪個節點左子樹的最後節點

(一直往上找,找到乙個節點是父節點的左孩子,則該父節點為後繼節點)

class node():

def __init__(self,item):

self.elem=item

self.lchild=none

self.rchild=none

self.parent=none

def getsuccessornode(node):

if node == none:

return node

if node.rchild != none: #沒有右子樹

return getleftmost(node.rchild)

else: #有右子樹

parent = node.parent

while parent != none and parent.lchild != node: #(3)

node = parent

parent = node.parent

return parent

def getleftmost( node): # 找最左節點

if node == none:

return node

while node.lchild != none:

node = node.lchild

return node

head=node(6)

head.parent=none

head.lchild=node(3)

head.lchild.parent=head

head.lchild.lchild =node(1)

head.lchild.lchild.parent = head.lchild

head.lchild.lchild.rchild =node(2)

head.lchild.lchild.rchild.parent = head.lchild.lchild

head.lchild.rchild =node(4)

head.lchild.rchild.parent = head.lchild

head.lchild.rchild.rchild=node(5)

head.lchild.rchild.rchild.parent = head.lchild.rchild

head.rchild=node(9)

head.rchild.parent=head

head.rchild.lchild =node(8)

head.rchild.lchild.parent = head.rchild

head.rchild.lchild.lchild =node(7)

head.rchild.lchild.lchild.parent = head.rchild.lchild

head.rchild.rchild =node(10)

head.rchild.rchild.parent = head.rchild

text=head.lchild.lchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.lchild.lchild.rchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.lchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.lchild.rchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.lchild.rchild.rchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.rchild.lchild.lchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.rchild.lchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.rchild

print(text.elem,"next:",getsuccessornode(text).elem)

text=head.rchild.rchild

print(text.elem,"next:",none)

二叉樹輸出其後繼節點

對於乙個二叉樹來講,其按中序遍歷,每個數後乙個數是這個數的後繼節點,那麼最後乙個數是沒有後繼節點的。根據中序遍歷的順序,乙個節點如果有右孩子,那麼右孩子最左邊的節點就是他的後繼節點,如果沒有右孩子,那麼這個節點是節點的父節點的左孩子就是其後繼節點,如果不是就繼續向上判斷,package zuoche...

快速找到二叉樹的後繼節點

設計乙個演算法,給定乙個二叉樹中的節點,返回它的後繼節點。該二叉樹的節點有父節點引用。二叉樹結點的後繼一般指的是中序遍歷中,該結點的後乙個結點。如果二叉樹的節點是沒有父節點的引用的。那麼對二叉樹進行中序遍歷可以很容易拿到指定節點的後繼節點。現在二叉樹的節點擁有父節點的引用,也就是說訪問二叉樹時不需要...

列印二叉樹中的後繼節點

思路 因為是中序遍歷後面的節點,所以如果乙個節點有右孩子的話,那麼後繼節點一定是右孩子那顆子樹上最左的節點。如果乙個節點沒有右孩子的話,先找到他的父節點,如果該節點是其其父節點的左孩子那麼父節點就是後繼節點,如果不是的話就繼續往上找。package lianxi04 public class cod...