144. 二叉树的前序遍历 LeetCode 力扣

给定一颗二叉树,返回他的前序遍历

解决思路:

遇到二叉树问题,如果深度不深,则可以直接用二叉树的递归遍历。

如果深度预计很深的话,可以用非递归遍历

public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        List<Integer> result = new ArrayList<>();
        add(result, root);
        return result;
    }
    private void add(List<Integer> result, TreeNode root) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        if (root.left != null) {
            add(result, root.left);
        }
        if (root.right != null) {
            add(result, root.right);
        }
    }

猜你喜欢

转载自blog.csdn.net/ZhaoXia_hit/article/details/106293130