LeetCode -- Binary Tree Preorder Traversal

Question:

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?

 

Analysis:

给出一棵二叉树,返回它节点值的先序遍历。

Note:递归的解法就太意思了,你能给出迭代的解决方法吗?

 

Answer:

1. Altough recursive solution is trivial,还是在这列一下吧,毕竟是解决树的问题的最简单的方案。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<Integer> res = new ArrayList<Integer>();
    public List<Integer> preorderTraversal(TreeNode root) {
        traversal(root);
        return res;
    }
    
    public void traversal(TreeNode root) {
        if(root == null)
            return;
        res.add(root.val);
        if(root.left != null)  traversal(root.left);
        if(root.right != null) traversal(root.right);
    }
    
}

 

2. 非递归的解决方案:需要借用栈辅助存储当前遍历节点的右子树节点。

     1)遍历当前节点;

     2)如果右子树不空,则右子树入栈保存;

     3)如果左子树不空,则指向左子树,遍历左子树;

     4)否则,就只好出栈咯,遍历右子树。

Answer:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<Integer>();
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(null);
        TreeNode p = root;
        while(!stack.isEmpty()) {
            list.add(p.val);
            if(p.right != null)
                stack.push(p.right);
            if(p.left != null)
                p = p.left;
            else 
                p = stack.pop();
        }
        return list;
    }
}

 

posted @ 2016-03-01 21:04  江湖小妞  阅读(174)  评论(0编辑  收藏  举报