爪哇中的二叉树PostOrder遍历
如果您想练习数据结构和算法程序,可以通过 前100多个数据结构和算法面试问题.
这是竞彩篮球分析二叉树教程的第3部分。
在这篇文章中,我们将了解竞彩篮球分析中的PostOrder二进制树遍历。
后订单遍历
- Traverse the
剩下 subtree
in PostOrder. - Traverse the
对 subtree
in PostOrder. Visit
节点。
有两种实现方式
- 递归的
- 迭代式
递归解决方案
递归解决方案非常简单,下图将使您更好地理解递归。
递归代码将是:
1 2 3 4 5 6 7 8 9 10 11 |
//递归解决方案 上市 虚空 后订单(树节点 根) { 如果(根 != 空值) { 后订单(根.剩下); 后订单(根.对); //通过打印节点数据来访问节点 系统.出.打印(“%d”,根.数据); } } |
迭代解决方案:
迭代解决方案的步骤:
- Create an empty stack
s
and set当前Node =root
. - 而
当前Node
is not NULL Do following- Push
当前Node 's 对 child
and then当前Node
to stacks
- 组
当前Node=currentNode.left
- Push
- Pop a node from stack
s
and set it to当前Node
- If the 流行音乐ped node has a
对 child
and the 对 child is at top of stack, thenremove
the 对 child from stack, 推 the当前Node
back and set当前Node
as当前Node 's 对 child
. - Else 打印
当前Node's 数据
and set当前Node
as NULL.
- If the 流行音乐ped node has a
- 堆栈不为空时,请重复步骤2和3。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
//迭代解决方案 上市 虚空 postorderIter( 树节点 根) { 如果( 根 == 空值 ) 返回; 叠放<树节点> s = 新 叠放<树节点>( ); 树节点 当前 = 根; 而( 真正 ) { 如果( 当前 != 空值 ) { 如果( 当前.对 != 空值 ) s.推( 当前.对 ); s.推( 当前 ); 当前 = 当前.剩下; 继续; } 如果( s.是空的( ) ) 返回; 当前 = s.流行音乐( ); 如果( 当前.对 != 空值 && ! s.是空的( ) && 当前.对 == s.窥视( ) ) { s.流行音乐( ); s.推( 当前 ); 当前 = 当前.对; } 其他 { 系统.出.打印( 当前.数据 + ” ); 当前 = 空值; } } } |
让我们创建用于postOrder遍历的竞彩篮球分析程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
包 组织.Arpit.爪哇2blog.二叉树; 进口 爪哇.实用程序.叠放; 上市 类 BinaryTreePostOrder { 上市 静态的 类 树节点 { 整型 数据; 树节点 剩下; 树节点 对; 树节点(整型 数据) { 这个.数据=数据; } } //递归解决方案 上市 虚空 后订单(树节点 根) { 如果(根 != 空值) { 后订单(根.剩下); 后订单(根.对); //通过打印节点数据来访问节点 系统.出.打印(“%d”,根.数据); } } //迭代解决方案 上市 虚空 postorderIter( 树节点 根) { 如果( 根 == 空值 ) 返回; 叠放<树节点> s = 新 叠放<树节点>( ); 树节点 当前 = 根; 而( 真正 ) { 如果( 当前 != 空值 ) { 如果( 当前.对 != 空值 ) s.推( 当前.对 ); s.推( 当前 ); 当前 = 当前.剩下; 继续; } 如果( s.是空的( ) ) 返回; 当前 = s.流行音乐( ); 如果( 当前.对 != 空值 && ! s.是空的( ) && 当前.对 == s.窥视( ) ) { s.流行音乐( ); s.推( 当前 ); 当前 = 当前.对; } 其他 { 系统.出.打印( 当前.数据 + ” ); 当前 = 空值; } } } 上市 静态的 虚空 主要(串[] args) { BinaryTreePostOrder 双=新 BinaryTreePostOrder(); //创建一个二叉树 树节点 根节点=createBinaryTree(); 系统.出.打印(“使用递归解决方案:”); 双.后订单(根节点); 系统.出.打印(); 系统.出.打印(“ -------------------------”); 系统.出.打印(“使用迭代解决方案:”); 双.postorderIter(根节点); } 上市 静态的 树节点 createBinaryTree() { 树节点 根节点 =新 树节点(40); 树节点 node20=新 树节点(20); 树节点 node10=新 树节点(10); 树节点 node30=新 树节点(30); 树节点 node60=新 树节点(60); 树节点 node50=新 树节点(50); 树节点 node70=新 树节点(70); 根节点.剩下=node20; 根节点.对=node60; node20.剩下=node10; node20.对=node30; node60.剩下=node50; node60.对=node70; 返回 根节点; } } |
运行上面的程序,您将获得以下输出:
10 30 20 50 70 60 40
————————-
使用迭代解决方案:
10 30 20 50 70 60 40
Comments
当最后一个左节点没有任何子节点时,会发生什么?