144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
非递归实现二叉树的前序遍历
java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> preorderTraversal(TreeNode root) { 12 List<Integer> res = new ArrayList<>() ; 13 Stack<TreeNode> stack = new Stack<>() ; 14 stack.push(root) ; 15 while(!stack.isEmpty()){ 16 TreeNode node = stack.pop() ; 17 if (node == null){ 18 continue ; 19 } 20 res.add(node.val) ; 21 stack.push(node.right) ; 22 stack.push(node.left) ; 23 } 24 return res ; 25 } 26 }