144. 二叉树的前序遍历

990 阅读1分钟

题目介绍

力扣144题:leetcode-cn.com/problems/bi…

image.png

方法一:递归

代码如下:

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null) {
            return result;
        }
        preorder(root,result);
        return result;
    }

    public void  preorder(TreeNode root,List<Integer> result) {
        if(root == null) {
            return;
        }
        //先遍历根节点
        result.add(root.val);
        preorder(root.left,result);
        preorder(root.right,result);
    }
    
}

方法一:迭代

首先我们应该创建一个Stack用来存放节点,首先我们想要打印根节点的数据,此时Stack里面的内容为空,所以我们优先将头结点加入Stack,然后打印。

之后我们应该先打印左子树,然后右子树。所以先加入Stack的就是右子树,然后左子树。 此时你能得到的流程如下:

image.png

代码如下:

public static void preOrderIteration(TreeNode head) {
    if (head == null) {
        return;
    }
    Stack<TreeNode> stack = new Stack<>();
    stack.push(head);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        System.out.print(node.value + " ");
        if (node.right != null) {
                stack.push(node.right);
        }
        if (node.left != null) {
                stack.push(node.left);
        }
    }
}