LintCode - 二叉树的前序遍历(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

给出一棵二叉树,返回其节点值的前序遍历。
样例给出一棵二叉树
{1,#,2,3}

 1 
   \ 
    2 
   / 
 3

返回 [1,2,3]

思路:非递归
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList list = new ArrayList();
        Stack stack = new Stack();  
        TreeNode node = root;  
        while(node != null || stack.size() > 0){  
            if(node != null){
                list.add(node.val);//压栈之前先访问  
                stack.push(node);//将所有左孩子压栈
                node = node.left;  
            }else{  
                node = stack.pop();  
                node = node.right;  
            }  
        }  
        return list;
    }
}
思路:递归
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList preorderTraversal(TreeNode root) {
        ArrayList result = new ArrayList();
        traverse(root, result);
        return result;
    }
    // 把root为跟的preorder加入result里面
    private void traverse(TreeNode root, ArrayList result) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        traverse(root.left, result);
        traverse(root.right, result);
    }
}

你可能感兴趣的:(LintCode - 二叉树的前序遍历(普通))