@@ -121,4 +121,54 @@ public List<Integer> preorderTraversal(TreeNode root) {
121121 }
122122 return list ;
123123 }
124+ }
125+
126+
127+ /*
128+ * 迭代思路:
129+ * 1、定义数据结构:结果列表存放排序节点值;节点列表按序存放节点;索引列表存放未判断是否有左右子节点的节点
130+ * 2、数据结构初始化:根节点存入节点列表;索引0存入索引列表
131+ * 3、迭代逻辑:
132+ * 1)索引列表不为空时,说明有节点未判断是否有左右子节点,循环遍历索引列表
133+ * 2)索引列表降序排序,取出最大索引,对该索引的节点进行操作。先处理靠右边的节点,可以防止插入节点时影响了节点列表其他节点的位置
134+ * 3)是否有子节点存在四种情况:有左右节点、只有右节点、只有左节点、没有左右节点。要分别处理,不同情况节点最终索引位置不同
135+ * 4)前序遍历:
136+ * 先插入右节点,再插入左节点
137+ * 插入左右节点都是在根节点右边插入,其他结点右移一位
138+ * 5)最大索引的节点判断完左右节点后,移除索引列表的最大索引
139+ * 6)最终节点列表按序排序,遍历结点列表,将节点值存入结果列表
140+ * */
141+ class Solution {
142+ public List <Integer > preorderTraversal (TreeNode root ) {
143+ List <Integer > resList = new ArrayList <>();
144+ if (root == null ) {
145+ return resList ;
146+ }
147+ List <TreeNode > nodeList = new ArrayList <>();
148+ List <Integer > indexList = new ArrayList <>();
149+ nodeList .add (root );
150+ indexList .add (0 );
151+ while (!indexList .isEmpty ()) {
152+ indexList .sort ((o1 , o2 ) -> o2 - o1 );
153+ int index = indexList .get (0 );
154+ root = nodeList .get (index );
155+ if (root .left != null && root .right != null ) {
156+ nodeList .add (index + 1 , root .right );
157+ nodeList .add (index + 1 , root .left );
158+ indexList .add (index + 2 );
159+ indexList .add (index + 1 );
160+ } else if (root .left != null ) {
161+ nodeList .add (index + 1 , root .left );
162+ indexList .add (index + 1 );
163+ } else if (root .right != null ) {
164+ nodeList .add (index + 1 , root .right );
165+ indexList .add (index + 1 );
166+ }
167+ indexList .remove (0 );
168+ }
169+ for (TreeNode node : nodeList ) {
170+ resList .add (node .val );
171+ }
172+ return resList ;
173+ }
124174}
0 commit comments