遍历二叉树笔记

二叉树的前序,中序,后序,层序遍历(递归与非递归)

// 前序遍历(递归)[N叉树的遍历同理]
class Solution {
    List<Integer> res = new ArrayList();
    public List<Integer> preorderTraversal(TreeNode root) {
        preorder(root);
        return res;
    }

    public void preorder(TreeNode root) {
        if (root != null) {
            res.add(root.val);
            preorder(root.left);
            preorder(root.right);
        }
    }
}

// 前序遍历(非递归)
// 入栈向左一直走,出栈转向右子树
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                root = root.right;
            }
        }
        return res;
    }
}

// 中序遍历(递归)
class Solution {
    List<Integer> res = new ArrayList();
    public List<Integer> inorderTraversal(TreeNode root) {
        inorder(root);
        return res;
    }
    public void inorder(TreeNode root) {
        if (root != null) {
            inorder(root.left);
            res.add(root.val);
            inorder(root.right);
        }
    }
}

// 中序遍历(非递归),总体思路与前序遍历大体相似。
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                res.add(root.val);
                root = root.right;
            }
        }
        return res; 
    }
}

// 二叉树的后序遍历(递归)
class Solution {
    List<Integer> res = new ArrayList();
    public List<Integer> postorderTraversal(TreeNode root) {
        postorder(root);
        return res;
    }
    public void postorder(TreeNode root) {
        if (root != null) {
            postorder(root.left);
            postorder(root.right);
            res.add(root.val);
        }
    }
}

// 二叉树的后序遍历(非递归)
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        TreeNode prev = null; // 用于标记刚刚已经访问过的结点
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.peek();
                // 关键注意此处的prev标识着刚刚已经访问过的右结点,防止迭代进入死循环
                if (root.right == null || root.right == prev) {
                    res.add(root.val);
                    stack.pop();
                    prev = root;
                    root = null;
                } else {
                  root = root.right;  
                }
            }
        }
        return res;
    }
}

// 二叉树的层序遍历(逐层地,从左到右访问所有节点)
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList();
            while (size > 0) {
                TreeNode temp = queue.poll();
                size--;
                level.add(temp.val);
                if (temp.left != null) queue.offer(temp.left);
                if (temp.right != null) queue.offer(temp.right);
            }
            result.add(level);
        }
        return result;
    }
}

二叉树的右视图

class Solution {
    // 比层序遍历更简单一点
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (size == 1) result.add(node.val);
                size--;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return result;
    }
}

二叉树的层平均值

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while (!queue.isEmpty()) {
            long sum = 0;  // 防止溢出
            int size = queue.size();
            int num = size;
            while (size > 0) {
                TreeNode node = queue.poll();
                sum += node.val;
                size--;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            result.add((double) sum / num);  // 强转成double提升精度
        }
        return result;
    }
}

填充每个节点的下一个右侧节点指针

// I(完美二叉树)
class Solution {
    // 层序遍历
    public Node connect(Node root) {
        if (root != null) {
            Queue<Node> queue = new LinkedList();
            queue.offer(root);
            Node pre = null;
            Node cur = null;
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size > 0) {
                    cur = queue.poll();
                    size--;
                    if (pre != null) pre.next = cur;
                    pre = cur;
                    if (cur.left != null) queue.offer(cur.left);
                    if (cur.right != null) queue.offer(cur.right);
                }
                // 每层遍历结束后,重置pre指针
                pre = null;
            }
        }
        return root;
    }
}

// II(普通二叉树)
// 尽管题目有些许差别,但解法其实是完全一样的
class Solution {
    public Node connect(Node root) {
        if (root != null) {
            Queue<Node> queue = new LinkedList();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    Node cur = queue.poll();
                    // 在遍历过程中,队列是发生变化的!(错误做法)
                    // if (queue.peek() != null) cur.next = queue.peek();
                    // 连接
                    if (i < size - 1) cur.next = queue.peek();
                    if (cur.left != null) queue.offer(cur.left);
                    if (cur.right != null) queue.offer(cur.right);
                }
            }
        }
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值