非递归实现二叉树的前序遍历
/* 144.二叉树的前序遍历
* 题目描述:采用非递归的方式对二叉树完成前序遍历
* 解题思路:
* 1
* 2 3
* 4 56 7
* 根节点入栈,弹出栈顶结点并访问,栈顶结点的右孩子左孩子入栈,重复该过程直到栈空
* 1入栈,1出栈输出32入栈,2出栈输出54入栈,4出栈输出,5出栈输出,3出栈输出76入栈。。
* */
public class BinaryTreePreorder {
}
//宽搜
class BinaryTreePreorderSolution1 {
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null) return new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if(node.right!=null) stack.push(node.right);
if(node.left!=null) stack.push(node.left);
}
return list;
}
}
//深搜
class BinaryTreePreorderSolution2{
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
TreeNode curr = root;
while(curr!=null||!stack.isEmpty()) {
while(curr!=null) {
list.add(curr.val);
stack.push(curr);
curr=curr.left;
}
curr=stack.pop().right;
}
return list;
}
}