Skip to content

Commit

Permalink
Merge pull request wangzheng0822#158 from LYDongD/my-algo/master
Browse files Browse the repository at this point in the history
add a new way for BT post order traverse
  • Loading branch information
wangzheng0822 authored Nov 23, 2018
2 parents ddbd68d + f1897d1 commit af1f4a5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
32 changes: 32 additions & 0 deletions go/24_tree/BinaryTree.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,35 @@ func (this *BinaryTree) PostOrderTraverse() {
fmt.Printf("%+v ", s2.Pop().(*Node).data)
}
}

//use one stack, pre cursor to traverse from post order
func (this *BinaryTree) PostOrderTraverse2() {
r := this.root
s := NewArrayStack()

//point to last visit node
var pre *Node

s.Push(r)

for !s.IsEmpty() {
r = s.Top().(*Node)
if (r.left == nil && r.right == nil) ||
(pre != nil && (pre == r.left || pre == r.right)) {

fmt.Printf("%+v ", r.data)
s.Pop()
pre = r
} else {
if r.right != nil {
s.Push(r.right)
}

if r.left != nil {
s.Push(r.left)
}

}

}
}
9 changes: 9 additions & 0 deletions go/24_tree/BinaryTree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,12 @@ func TestBinaryTree_PostOrderTraverse(t *testing.T) {

binaryTree.PostOrderTraverse()
}

func TestBinaryTree_PostOrderTraverse2(t *testing.T) {
binaryTree := NewBinaryTree(1)
binaryTree.root.left = NewNode(3)
binaryTree.root.right = NewNode(4)
binaryTree.root.right.left = NewNode(5)

binaryTree.PostOrderTraverse2()
}

0 comments on commit af1f4a5

Please sign in to comment.