二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
List<Integer> retList = new ArrayList<>();
/**
* 二叉树的后序遍历:递归
* @param root
* @return
*/
public List<Integer> postorderTraversal(TreeNode root) {
if(root != null){
postorderTraversal(root.left);
postorderTraversal(root.right);
retList.add(root.val);
}
return retList;
}
进阶:
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
Stack<Pair<TreeNode,Boolean>> stack = new Stack<Pair<TreeNode, Boolean>>();
stack.push(new Pair<TreeNode, Boolean>(root,false));
while (!stack.empty()){
Pair<TreeNode,Boolean> p = stack.pop();
if(p.getValue().equals(true)){
ret.add(p.getKey().val);
}else {
stack.add(new Pair<TreeNode, Boolean>(p.getKey(),true));
if(p.getKey().right != null){
stack.push(new Pair<TreeNode, Boolean>(p.getKey().right,false));
}
if(p.getKey().left != null){
stack.add(new Pair<TreeNode, Boolean>(p.getKey().left,false));
}
}
}
return ret;
}
/**
* 二叉树的后序遍历:非递归(栈)模拟系统指令
* @param root
* @return
*/
public class Command{
String s;//go,print
TreeNode node;
Command(String s,TreeNode node){this.s = s;this.node= node;}
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> retList = new ArrayList<>();
if(root == null){
return retList;
}
Stack<Command> stack = new Stack<>();
//入栈
stack.push(new Command("go",root));
while (! stack.empty()){
//将栈顶元素推出
Command command = stack.pop();
if(command.s == "print"){
retList.add(command.node.val);
}else{
stack.push(new Command("print",command.node));
//command.s == "go"
if(command.node.right !=null){
//先右孩子入栈
stack.push(new Command("go",command.node.right));
}
if(command.node.left != null){
//再左孩子入栈
stack.push(new Command("go",command.node.left));
}
}
}
return retList;
}