标签:push 通过 code tor 代码 null new return integer
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
后序遍历顺序是 left->right->root
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 迭代版
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
LinkedList<TreeNode> s = new LinkedList<>();
TreeNode current = root, isVisited = null;
while (current != null || !s.isEmpty()){
while (current != null){
s.push(current);
current = current.left;
}
current = s.peek();
if (current.right == null || current.right == isVisited){
s.pop();
res.add(current.val);
isVisited = current;
current = null;
}else {
current = current.right;
}
}
return res;
}
}
标签:push 通过 code tor 代码 null new return integer
原文地址:https://www.cnblogs.com/Tu9oh0st/p/10908760.html