[144] LeetCode preorder traversal of a binary tree

Title:
Given a binary tree in preorder traversal to return it.

Example:

Input: [. 1, null, 2,3]
. 1

2
/
. 3

Output: [1,2,3]

	public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list= new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root==null)
            return list;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            list.add(temp.val);
            if(temp.right!=null)
                stack.push(temp.right);
            if(temp.left!=null)
                stack.push(temp.left);
        }
        return list;
    }
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/103755917