https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
很简单,递归。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List list = new ArrayList<Integer>(); if(root == null){ return list; } list.add(root.val); list.addAll(preorderTraversal(root.left)); list.addAll(preorderTraversal(root.right)); return list; } }
但原题提出不用递归的方法,即遍历。使用stack,遇到一个节点,首先处理该节点,即list.add(root.val)。如果右节点不为空,将右节点推入stack,留在后面弹出使用。这时如果左节点不为空,下移到左节点,处理左子树。如果左节点为空,从stack中弹出最上面的节点作为下一个节点。
循环上述过程,直到当前处理节点为空。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while(root!= null){ list.add(root.val); if(root.right != null){ stack.push(root.right); } if(root.left != null){ root = root.left; }else{ if(!stack.empty()){ root = stack.pop(); }else{ root = null; } } } return list; } }
下面是另一个比较简单的版本,也是推荐的。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while(!stack.empty() || root != null){ if(root != null){ list.add(root.val); if(root.right != null){ stack.push(root.right); } root = root.left; }else{ root = stack.pop(); } } return list; } }