侧边栏壁纸
博主头像
warlock博主等级

夏响青篁冬悦雪, 昼巡红镜夜观天

  • 累计撰写 11 篇文章
  • 累计创建 6 个标签
  • 累计收到 0 条评论
标签搜索

目 录CONTENT

文章目录

笔记——树的遍历

warlock
2024-07-31 / 0 评论 / 0 点赞 / 221 阅读 / 354 字

广度优先搜索(层序遍历)可以采用队列来实现

public List<Integer> levelOrder(TreeNode root) {

    Queue<TreeNode> queue = new LinkedList<>();  
    List<Integer> list = new ArrayList<>();  

    if (root != null) {
        queue.offer(root);  // ① 搜索起点入队
    }

    while (!queue.isEmpty()) {
        
        TreeNode head = queue.poll();
        list.add(head.val);  // ② 队列头部弹出
        
        if (head.left != null) {   
            queue.add(head.left);  // ③ 左孩子入队
        }
        if (head.right != null) {
            queue.add(head.right);  // ④ 右孩子入队
        }
    }
    return list;
}

广度优先搜索

深度优先(前、中、后序遍历)可以用栈来实现
前序遍历

//前序遍历
public void preOrderTraveralWithStack(TreeNode root) {
    Stack stack = new Stack<>();
    TreeNode treeNode = root;
    while (treeNode != null || !stack.isEmpty()) {
        //不断往栈中压入左节点,直到左边没有左节点
        while (treeNode != null) {
            System.out.println(treeNode.val);
            stack.push(treeNode);
            treeNode = treeNode.left;
        }
        //弹栈 访问右边节点
        if (!stack.isEmpty()) {
            treeNode = stack.pop();
            treeNode = treeNode.right;
        }
    }
}

前序
中序遍历

public void middleOrderTraversal(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    TreeNode treeNode = root;
    while (treeNode != null || !stack.isEmpty()) {
        //不断往栈中压入左节点,直到左边没有左节点
        while (treeNode != null) {
            stack.push(treeNode);
            treeNode = treeNode.left;
        }
        //弹栈 访问右边节点
        if (!stack.isEmpty()) {
            treeNode = stack.pop();
            System.out.println(treeNode.val);
            treeNode = treeNode.right;
        }
    }
}

中序
后序遍历

public List<Integer> postOrderTraversal(TreeNode root) {
    LinkedList<Integer> res = new LinkedList<>();
    if (root == null) {
        return res;
    }
    LinkedList<TreeNode> stack = new LinkedList<>();
    stack.add(root);
    while (!stack.isEmpty()) {
        TreeNode pop = stack.pop();
        res.add(pop.val);
        if (pop.left != null) {
            stack.push(pop.left);
        }
        if (pop.right != null) {
            stack.push(pop.right);
        }
    }
    Collections.reverse(res);
    return res;
}

后序

0

评论区