领扣LintCode算法问题答案-1783. 二叉树的后序遍历
目录
1783. 二叉树的后序遍历描述样例 1:样例 2:
题解鸣谢
1783. 二叉树的后序遍历
描述
给出一棵二叉树,返回其节点值的后序遍历。
首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
样例 1:
输入:{1,2,3}
输出:[2,3,1]
解释:
1
/ \
2 3
样例 2:
输入:{1,2,#,3,4}
输出:[3,4,2,1]
解释:
1
/
2
/ \
3 4
题解
public class Solution {
public List
<Integer> postorderTraversal(TreeNode root
) {
List
<Integer> ret
= new ArrayList<>();
Stack
<TreeNode> stack
= new Stack<TreeNode>();
Stack
<TreeNode> output
= new Stack<TreeNode>();
TreeNode node
= root
;
while (node
!= null
|| !stack
.isEmpty()) {
if (node
!= null
) {
stack
.push(node
);
output
.push(node
);
node
= node
.right
;
} else {
node
= stack
.pop();
node
= node
.left
;
}
}
while (!output
.isEmpty()) {
TreeNode n
= output
.pop();
ret
.add(n
.val
);
}
return ret
;
}
}
原题链接点这里
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。