求给定的二叉树的前序遍历。
例如:
给定的二叉树为{1,#,2,3},
非递归前序遍历二叉树
思路和后续是一样的,用两个Stack来辅助我们进行。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.ArrayList; import java.util.Stack; public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result= new ArrayList<Integer>(); if(root == null)return result; result.add(root.val); Stack<TreeNode> stackNode = new Stack<>(); Stack<Integer> stackFlag = new Stack<>(); stackNode.push(root); stackFlag.push(0); while(!stackNode.isEmpty()){ TreeNode tempNode = stackN