LeetCode【144】二叉树的前序遍历

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

示例:

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

2
/
3

输出: [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;
    }
发布了55 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq422243639/article/details/103755917