二叉树的前序、中序、后序遍历:
递归实现:不同顺序改变递归就行。
前序:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null){
return list;
}else{
list.add(root.val);
list.addAll(preorderTraversal(root.left));
list.addAll(preorderTraversal(root.right));
}
return list;
}
}
非递归实现:即用栈模拟系统递归的实现,为了更方便理解,将节点信息封装一下,这样完全模拟系统递归了,其他顺序也只需要像递归实现一样改变顺序就好了。这里不同与书本的每种顺序各有个的非递归实现。
//非递归遍历二叉树,用stack模拟系统栈,根据递归思路实现,前中后一样。
public class L144BTreeTravesal {
public static List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<Command> stack = new Stack<Command>();
if(root == null){
return list;
}
stack.push(new Command(false, root));
while(!stack.isEmpty()){
Command curr = stack.pop();
if(curr.isOut){
list.add(curr.node.val);
}else{
if(curr.node.right != null){
stack.push(new Command(false,curr.node.right));
}
if(curr.node.left != null){
stack.push(new Command(false,curr.node.left));
}
stack.push(new Command(true, curr.node));
}
}
return list;
}
}
class Command{
boolean isOut;
TreeNode node;
public Command(boolean isOut, TreeNode node) {
this.isOut = isOut;
this.node = node;
}
}
非递归中序遍历:
public static List<Integer> solution(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
TreeNode p = root;
Stack stack = new Stack();
stack.push(p);
p = p.left;
while (!stack.isEmpty()) {
while (p != null) {
stack.push(p);
p = p.left;
}
if (!stack.isEmpty()) {
TreeNode temp = (TreeNode) stack.pop();
list.add(temp.val);
p = temp.right;
} else {
return list;
}
}
return list;
}
非递归后序遍历:
public static List<Integer> solution(TreeNode root){
Stack<TreeNode> stack = new Stack();
Stack<TreeNode> outPut = new Stack();
List<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
stack.push(root);
while(!stack.isEmpty()) {
TreeNode p = stack.pop();
outPut.push(p);
if(p.left != null){
stack.push(p.left);
}
if(p.right != null){
stack.push(p.right);
}
}
while (!outPut.isEmpty() ) {
list.add(outPut.pop().val);
}
return list;
}