For example: java
Given binary tree {1,#,2,3}, spa
1 \ 2 / 3
return [1,2,3]. code
分析:此題考查二叉樹的前序遍歷,此處使用非遞歸遍歷方式實現
public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); TreeNode p = root;
//雙端隊列,實現棧的功能 Deque<TreeNode> stack = new ArrayDeque<>(); while(p!=null || !stack.isEmpty()){ while(p!= null){ list.add(p.val); stack.push(p); p = p.left; } if(!stack.isEmpty()){ p = stack.pop(); p = p.right; } } return list; } }