二叉树前序遍历
求二叉树的前序遍历
http://www.nowcoder.com/questionTerminal/501fb3ca49bb4474bf5fa87274e884b4
非递归求解前序二叉树
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList */ public ArrayList<Integer> preorderTraversal (TreeNode root) { // write code here ArrayList<Integer> res = new ArrayList<>(); if(root == null) return res; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.isEmpty()){ TreeNode node = st.pop(); res.add(node.val); if(node.right != null){st.push(node.right);} if(node.left != null){st.push(node.left);} } return res; } }