import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* post order traverse tree
* @author LS
* 二叉树递归和非递归两种实现方式
*/
public class Solution {
private List<Integer> result = new ArrayList<Integer>();
/**
* 后续遍历递归实现
*/
public List<Integer> postorderTraversal(TreeNode root) {
if(result == null){
result = new ArrayList<Integer>();
}
if(root == null){
return result;
}
if(root.left != null){
postorderTraversal(root.left);
}
if(root.right != null){
postorderTraversal(root.right);
}
result.add(root.val);
return result;
}
/**
* 前序遍历非递归实现 依次将根入栈,弹出时放入右、左节点
*/
public ArrayList<Integer> preorderTraversal2(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
if(root != null){
s.push(root);
while(!s.isEmpty()){
TreeNode tmp = s.pop();
result.add(tmp.val);
if(tmp.right != null){
s.push(tmp.right);
}
if(tmp.left != null){
s.push(tmp.left);
}
}
}
return result;
}
/**
* 中序遍历非递归实现 根入栈,循环左子节点入栈,弹出时压入右子节点
*/
public ArrayList<Integer> inOrderTraversal2(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
TreeNode node = root;
while(node != null || !s.isEmpty()){
while(node != null){
s.push(node);
node = node.left;
}
if(!s.isEmpty()){
node = s.pop();
result.add(node.val);
node = node.right;
}
}
return result;
}
/**
* 后续遍历非递归实现 双栈法
*/
public ArrayList<Integer> postrderTraversal2(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
Stack<TreeNode> tmp = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
TreeNode node = root;
while(node != null || !s.isEmpty()){
while(node != null){
s.push(node);
tmp.push(node);
node = node.right;
}
if(!s.isEmpty()){
node = s.pop();
node = node.left;
}
}
while(!tmp.isEmpty()){
result.add(tmp.pop().val);
}
return result;
}
leetcode 二叉树遍历非递归实现
最新推荐文章于 2021-09-27 00:24:08 发布