144. 二叉树前序遍历
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] cur = root stack = [] while cur or stack: while cur : res.append(cur.val) stack.append(cur) cur = cur.left t = stack.pop() cur = t.right return res
1 class Solution { 2 private List<Integer> res = new ArrayList<Integer>(); 3 public List<Integer> preorderTraversal(TreeNode root) { 4 help(root); 5 return res; 6 } 7 private void help(TreeNode root){ 8 if(root == null) return ; 9 res.add(root.val); 10 help(root.left); 11 help(root.right); 12 } 13 }