二叉樹理論基礎
1.二叉樹的種類:滿二叉樹:深度為k,有2^k-1個節點的二叉樹;完全二叉樹:除最後一層外的所有層全滿,而且最後一層的結點集中在最左邊,中間不能空
2.二叉搜尋樹:若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;它的左、右子樹也分別為二叉搜尋樹
3.平衡二叉搜尋樹:在二叉搜尋樹的基礎上。左右子樹的高度差絕對值不超過1。(題外話:HashMap/HashSet: 雜湊表實現,平均時間複雜度 O(1);TreeMap/TreeSet: 紅黑樹實現,時間複雜度 O(log n);LinkedHashMap/LinkedHashSet: 雜湊表 + 雙向連結串列,保持插入順序;ConcurrentHashMap: 分段鎖/紅黑樹 + 雜湊表,適用於併發場景。)
4.二叉樹的儲存方式:二叉樹可以鏈式儲存,也可以順序儲存(陣列:i,左2i+1,右2i+2)。
5.二叉樹的遍歷方式:深度優先遍歷:前序遍歷(中左右)、中序遍歷(左中右)、後序遍歷(左右中);廣度優先遍歷:層次遍歷(迭代法)
6.二叉樹的定義:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
二叉樹的前序遍歷
題目連結:144.二叉樹的前序遍歷
文件講解︰程式碼隨想錄(programmercarl.com)
日期:2024-09-09
想法:1.遞迴:遞迴三要素:確定遞迴函式的引數和返回值,確定終止條件,確定單層遞迴的邏輯;2.迭代:遞迴的實現就是:每一次遞迴呼叫都會把函式的區域性變數、引數值和返回地址等壓入呼叫棧中,所以用棧來做迭代法,入棧根結點,每次取“中“位置的,再入棧右左(出棧是才能是左右)。
Java程式碼如下:
//遞迴
class Solution {
public void preOrder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
list.add(root.val);
preOrder(root.left, list);
preOrder(root.right, list);
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
preOrder(root, list);
return list;
}
}
//迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
List<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
st.push(root);
while(!st.isEmpty()){
TreeNode node = st.pop();
list.add(node.val);
if(node.right != null){
st.push(node.right);
}
if(node.left != null){
st.push(node.left);
}
}
return list;
}
}
總結:前序中左右,遞迴確定三要素,遞迴函式的引數和返回,遞迴中止條件,單層邏輯;迭代用棧來完成,想象怎麼進,出的時候才能順序正確。
二叉樹的後序遍歷
題目連結:145.二叉樹的後序遍歷
文件講解︰程式碼隨想錄(programmercarl.com)
日期:2024-09-09
Java程式碼如下:
//遞迴
class Solution {
public void postOrder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
postOrder(root.left, list);
postOrder(root.right, list);
list.add(root.val);
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
postOrder(root, list);
return list;
}
}
//迭代
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> st = new ArrayDeque<>();
List<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
st.push(root);
while(!st.isEmpty()){
TreeNode node = st.pop();
list.add(node.val);
if(node.left != null){
st.push(node.left);
}
if(node.right != null){
st.push(node.right);
}
}
Collections.reverse(list);
return list;
}
}
總結:後序左右中(中右左反著),跟前序很類似。
二叉樹的中序遍歷
題目連結:94.二叉樹的中序遍歷
文件講解︰程式碼隨想錄(programmercarl.com)
日期:2024-09-09
想法:中序遍歷是左中右,先訪問的是二叉樹頂部的節點,然後一層一層向下訪問,直到到達樹左面的最底部,再開始處理節點,需要借用指標的遍歷來幫助訪問節點,棧則用來處理節點上的元素
Java程式碼如下:
//遞迴
class Solution {
public void inOrder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
inOrder(root, list);
return list;
}
}
//迭代
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null){
return result;
}
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !st.isEmpty()){
if (cur != null){
st.push(cur);
cur = cur.left;
}else{
cur = st.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
總結:中序,左中右,迭代法與前後序不一樣,得先左邊走到底,再中,再右。
二叉樹的層序遍歷
題目連結:102.二叉樹的層序遍歷
107.二叉樹的層次遍歷II
199.二叉樹的右檢視
637.二叉樹的層平均值
429.N叉樹的層序遍歷
515.在每個樹行中找最大值
116.填充每個節點的下一個右側節點指標
117.填充每個節點的下一個右側節點指標II
104.二叉樹的最大深度
111.二叉樹的最小深度
文件講解︰程式碼隨想錄(programmercarl.com)
日期:2024-09-09
Java程式碼如下:
//二叉樹的層序遍歷
class Solution {
public List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
check(root);
return res;
}
public void check(TreeNode node) {
if (node == null) return;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(node);
while (!que.isEmpty()) {
List<Integer> itemList = new ArrayList<Integer>();
int len = que.size();
while (len > 0) {
TreeNode tmpNode = que.poll();
itemList.add(tmpNode.val);
if (tmpNode.left != null) que.offer(tmpNode.left);
if (tmpNode.right != null) que.offer(tmpNode.right);
len--;
}
res.add(itemList);
}
}
}
//二叉樹的層次遍歷II
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
List<Integer> levelList = new ArrayList<>();
int levelSize = que.size();
for (int i = 0; i < levelSize; i++) {
TreeNode peek = que.peekFirst();
levelList.add(que.pollFirst().val);
if (peek.left != null) {
que.offerLast(peek.left);
}
if (peek.right != null) {
que.offerLast(peek.right);
}
}
list.add(levelList);
}
List<List<Integer>> result = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i-- ) {
result.add(list.get(i));
}
return result;
}
}
//二叉樹的右檢視
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
int levelSize = que.size();
for (int i = 0; i < levelSize; i++) {
TreeNode poll = que.pollFirst();
if (poll.left != null) {
que.addLast(poll.left);
}
if (poll.right != null) {
que.addLast(poll.right);
}
if (i == levelSize - 1) {
list.add(poll.val);
}
}
}
return list;
}
}
//二叉樹的層平均值
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
int levelSize = que.size();
double levelSum = 0.0;
for (int i = 0; i < levelSize; i++) {
TreeNode poll = que.pollFirst();
levelSum += poll.val;
if (poll.left != null) {
que.addLast(poll.left);
}
if (poll.right != null) {
que.addLast(poll.right);
}
}
list.add(levelSum / levelSize);
}
return list;
}
}
//N 叉樹的層序遍歷
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> list = new ArrayList<>();
Deque<Node> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
int levelSize = que.size();
List<Integer> levelList = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
Node poll = que.pollFirst();
levelList.add(poll.val);
List<Node> children = poll.children;
if (children == null || children.size() == 0) {
continue;
}
for (Node child : children) {
if (child != null) {
que.offerLast(child);
}
}
}
list.add(levelList);
}
return list;
}
}
//在每個樹行中找最大值
class Solution {
public List<Integer> largestValues(TreeNode root) {
if(root == null){
return Collections.emptyList();
}
List<Integer> result = new ArrayList();
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
int max = Integer.MIN_VALUE;
for(int i = queue.size(); i > 0; i--){
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
result.add(max);
}
return result;
}
}
//填充每個節點的下一個右側節點指標
class Solution {
public Node connect(Node root) {
Queue<Node> tmpQueue = new LinkedList<Node>();
if (root != null) tmpQueue.add(root);
while (tmpQueue.size() != 0){
int size = tmpQueue.size();
Node cur = tmpQueue.poll();
if (cur.left != null) tmpQueue.add(cur.left);
if (cur.right != null) tmpQueue.add(cur.right);
for (int index = 1; index < size; index++){
Node next = tmpQueue.poll();
if (next.left != null) tmpQueue.add(next.left);
if (next.right != null) tmpQueue.add(next.right);
cur.next = next;
cur = next;
}
}
return root;
}
}
//填充每個節點的下一個右側節點指標II
class Solution {
public Node connect(Node root) {
Queue<Node> queue = new LinkedList<>();
if (root != null) {
queue.add(root);
}
while (!queue.isEmpty()) {
int size = queue.size();
Node node = null;
Node nodePre = null;
for (int i = 0; i < size; i++) {
if (i == 0) {
nodePre = queue.poll();
node = nodePre;
} else {
node = queue.poll();
nodePre.next = node;
nodePre = nodePre.next;
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
nodePre.next = null;
}
return root;
}
}
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
int depth = 0;
while (!que.isEmpty())
{
int len = que.size();
while (len > 0)
{
TreeNode node = que.poll();
if (node.left != null) que.offer(node.left);
if (node.right != null) que.offer(node.right);
len--;
}
depth++;
}
return depth;
}
}
//二叉樹的最小深度
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()){
int size = queue.size();
depth++;
TreeNode cur = null;
for (int i = 0; i < size; i++) {
cur = queue.poll();
if (cur.left == null && cur.right == null){
return depth;
}
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return depth;
}
}