1. 力扣101 : 對稱二叉樹
(1). 題
給你一個二叉樹的根節點?root
?, 檢查它是否軸對稱。
示例 1:
?
輸入:root = [1,2,2,3,4,4,3] 輸出:true
示例 2:
?
輸入:root = [1,2,2,null,3,null,3] 輸出:false
提示:
- 樹中節點數目在范圍?
[1, 1000]
?內 -100 <= Node.val <= 100
(2). 思路
用隊列將二叉樹的根節點的左子樹和右子樹的值記錄下來,然后while循環比較.
(3). 解
class Solution {Deque<Integer> deque1 = new LinkedList<>();Deque<Integer> deque2 = new LinkedList<>();public boolean isSymmetric(TreeNode root) {boolean flag = true;recursionLeft(root.left);recursionRight(root.right);while (!deque1.isEmpty() && !deque2.isEmpty()) {if (deque1.poll() != deque2.poll()) {flag = false;}}return flag;}public void recursionLeft(TreeNode root) {if (root == null) {deque1.offer(110);return;}deque1.offer(root.val);recursionLeft(root.left);recursionLeft(root.right);}public void recursionRight(TreeNode root) {if (root == null) {//這處代碼是需要的, 不然光靠根左右是無法確定是否是對稱的deque2.offer(110);return;}deque2.offer(root.val);recursionRight(root.right);recursionRight(root.left);}
}
2. 力扣104 : 二叉樹的最大深度
(1). 題
給定一個二叉樹?root
?,返回其最大深度。
二叉樹的?最大深度?是指從根節點到最遠葉子節點的最長路徑上的節點數。
示例 1:
?
?
輸入:root = [3,9,20,null,null,15,7] 輸出:3
示例 2:
輸入:root = [1,null,2] 輸出:2
提示:
- 樹中節點的數量在?
[0, 104]
?區間內。 -100 <= Node.val <= 100
(2). 思路
遞歸,從根節點開始,樹的最大高度就是,根節點+左孩子的高度/右孩子的高度.而該左孩子的高度為左孩子+左孩子的左孩子的高度/左孩子的右孩子高度...
(3). 解
class Solution {public int maxDepth(TreeNode root) {if (root == null) {return 0;}int a = maxDepth(root.left);int b = maxDepth(root.right);a = a > b ? a : b;return 1 + a;}
}
3. 力扣111 : 二叉樹的最小深度
(1). 題
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明:葉子節點是指沒有子節點的節點。
示例 1:
?
輸入:root = [3,9,20,null,null,15,7] 輸出:2
示例 2:
輸入:root = [2,null,3,null,4,null,5,null,6] 輸出:5
提示:
- 樹中節點數的范圍在?
[0, 105]
?內 -1000 <= Node.val <= 1000
(2). 思路
與求解二叉樹的最大二叉樹代碼不同的是,題目要求根節點到最近葉子節點的高度,對于根節點只有左子樹(或只有右子樹)這種情況來說,需要額外討論,因為此時不能直接返回1,而是要返回1+右子樹的高度.
(3). 解
class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}if (root.left == null) {return 1 + minDepth(root.right);}if (root.right == null) {return 1 + minDepth(root.left);}int a = minDepth(root.left);int b = minDepth(root.right);a = a < b ? a : b;return a + 1;}
}