LeetCode144 二叉树的前序遍历

LeetCode144 二叉树的前序遍历_第1张图片

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

//非递归:
class Solution {
    
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        if(root==null)
            return list;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);
            if(node.right!=null)
                stack.push(node.right);
            if(node.left!=null)
                stack.push(node.left);
        }
        return list;
    }
}

 

你可能感兴趣的:(剑指offer)