1、前序
//Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node>; _children) {
val = _val;
children = _children;
}
};
class Solution {
public List<Integer> postorder(Node root) {
Stack<Node> s = new Stack<>();
List<Integer> result = new LinkedList<>();
Node x;
if(root!=null){
s.push(root);
}else{
return result;
}
while(!s.isEmpty()){
x = s.pop();
result.add(x.val);
for(int i = x.children.size()-1;i>-1;i++){
s.push(x.children.get(i));
}
}
return result;
}
}
2、后序
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
class Solution {
public List<Integer> postorder(Node root) {
Stack<Node> s = new Stack<>();
List<Integer> result = new LinkedList<>();
Node x;
if(root!=null){
s.push(root);
}else{
return result;
}
while(!s.isEmpty()){
x = s.pop();
for(Node n:x.children){
s.push(n);
}
result.add(0,x.val);
}
return result;
}
}
额外:二叉树的中序遍历
class solution{
private List<Integer> result = new LinkedList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
do {
//依次将左节点均加入栈中
while(root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
result.add(root.val);
//这一步若右节点为null则用于躲避上面的while循环
//若不为null则会将右节点上面的循环入栈
//因此出栈顺序是最深处的左中右(右无子树,若有还要延迟该层右节点的出栈)
root = root.right;
}
} while(!stack.isEmpty() || root != null);
return result;
}
}
总结:
由于N叉树没有左子树右子树这样说法,所以没用中序遍历方式,这三种方式用递归较为简单,而迭代由于其输出的不同需要要用到堆栈这一特性,即FILO,但是在树的层次遍历中,由于是父亲节点优先于子节点,既遵循FIFO,故采用队列。