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?
二叉树的先序遍历。
这个比较简单,直接看递归和非递归的代码实现
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); process(root,list); return list; } public void process(TreeNode node,List<Integer> list){ if(node==null){ return; } list.add(node.val); process(node.left,list); process(node.right,list); } }
先序遍历:中左右
非递归的方式用stack来实现(深度优先遍历用stack,广度优先用队列)
对当前节点压入stack,弹出并打印(中),再对cur压入右左(左右)
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); if(root==null){ return list; } Stack<TreeNode> stack=new Stack<>(); stack.push(root); while(!stack.isEmpty()){ TreeNode cur=stack.pop(); list.add(cur.val); if(cur.right!=null){ stack.push(cur.right); } if(cur.left!=null){ stack.push(cur.left); } } return list; } }