1. 树的概念
1.1 满二叉树、完全二叉树、二叉搜索树
满二叉树:高度为h,由2^h-1个节点构成的二叉树称为满二叉树;
完全二叉树:完全二叉树是由满二叉树而引出来的,若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数(即1~h-1层为一个满二叉树),第 h 层所有的结点都连续集中在最左边,堆一般都是用完全二叉树实现的;
二叉搜索树:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
1.2 前驱节点、后继节点
前驱节点:对一棵二叉树进行中序遍历,遍历后的顺序,当前节点的前一个节点为该节点的前驱节点;
后继节点:对一棵二叉树进行中序遍历,遍历后的顺序,当前节点的后一个节点为该节点的后继节点;
1.3 二叉树性质
2. 二叉树遍历
2.1 前序遍历
//递归 private void preOrderR(TreeNode head) { if (head == null) { return; } System.out.print(head.val + " "); preOrderR(head.left); preOrderR(head.right); } // 先入栈右子节点 再入栈左子节点 private void preOrder(TreeNode head) { Deque<TreeNode> stack = new LinkedList<>(); stack.push(head); while (!stack.isEmpty()) { System.out.print(head.val + " "); TreeNode node = stack.pop(); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } System.out.println(); }
2.2 中序遍历
//递归 private void inOrderR(TreeNode head) { if (head == null) { return; } preOrderR(head.left);
System.out.print(head.val + " "); preOrderR(head.right); } private void inOrder(TreeNode head) { System.out.println("===in-order==="); if (head == null) { return; } Deque<TreeNode> stack = new LinkedList<>(); TreeNode node = head; while (!stack.isEmpty() || node != null) { if (node != null) { // 压入二叉树左斜边 stack.push(node); node = node.left; } else { node = stack.pop(); System.out.println(node.val + " "); node = node.right; } } System.out.println(); }
2.3 后序遍历
//递归 private void postOrderR(TreeNode head) { if (head == null) { return; } preOrderR(head.left); preOrderR(head.right);
System.out.print(head.val + " "); } private void postOrder(TreeNode head) { System.out.println("===post-order==="); if (head == null) { return; } Deque<TreeNode> stack = new LinkedList<>(); Deque<TreeNode> stack2 = new LinkedList<>(); stack.push(head); TreeNode node; while (!stack.isEmpty()) { // pop and stack store node = stack.pop(); stack2.push(node); // push left node if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } while (!stack2.isEmpty()) { System.out.print(stack2.pop().val + " "); } }
2.4 广度遍历
public void level(TreeNode head) { if (head == null) { return; } Deque<TreeNode> queue = new LinkedList<>(); queue.offer(head); while (!queue.isEmpty()) { TreeNode cur = queue.poll(); System.out.println(cur.val + " "); if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } }
基于上述的按层遍历二叉树代码,现有如下题目:求二叉树最大宽度 https://leetcode-cn.com/problems/maximum-width-of-binary-tree/