144. 二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]
  1
   \
   2
   /
  3

输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        Listpre =  new LinkedList<>();
        preorder(root,pre);
        return pre;
    }
    public void preorder(TreeNode root,Listans){
        if(root == null){
            return;
        }
        ans.add(root.val);
        preorder(root.left,ans);
        preorder(root.right,ans);
    }
}

迭代:

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

推荐使用LinkedList来模拟Stack,时间会更快,因为Stack的底层是vector

你可能感兴趣的:(144. 二叉树的前序遍历)