[leetcode] 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?


分析:也就是求二叉树的先序遍历。

思路一:递归,DFS求解。比较简单

 1 class Solution {
 2     List<Integer> res = new ArrayList<Integer>();
 3     public List<Integer> preorderTraversal(TreeNode root) {
 4         helper(root);
 5         return res;
 6     }
 7     private void helper(TreeNode root){
 8         if ( root == null ) return ;
 9         res.add(root.val);
10         helper(root.left);
11         helper(root.right);
12     }
13 }

思路二:非递归方法实现。真正面试如果考到二叉树的三种遍历方法,肯定是考非递归,也就是栈的方法来实现的。

参考:https://www.cnblogs.com/boris1221/p/9398848.html

 1 class Solution {
 2     public List<Integer> preorderTraversal(TreeNode root) {
 3         List<Integer> list = new ArrayList<>();
 4         if ( root == null ) return list;
 5         Stack<TreeNode> stack = new Stack<>();
 6         stack.push(root);
 7         while ( !stack.isEmpty() ){
 8             while ( root != null ){
 9                 list.add(root.val);
10                 stack.push(root);
11                 root = root.left;
12             }
13             if ( !stack.isEmpty() ){
14                 root = stack.pop().right;
15             }
16         }
17         return list;
18     }
19 }

 

posted @ 2018-10-18 15:10  Lin.B  阅读(85)  评论(0编辑  收藏  举报