想了解更多數據結構以及算法題,可以關注微信公衆號“數據結構和算法”,每天一題爲你精彩解答。也可以掃描下面的二維碼關注
問題
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
數據結構:
java:樹節點的數據結構
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
C語言:樹節點的數據結構
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
C++:樹節點的數據結構
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
遞歸寫法
我們能想到的最簡單的方式估計就是遞歸了,也就是下面這個圖
如果對遞歸不熟悉的話可以看下我前面講的關於復仇一個故事362,漢諾塔。下面我們來畫個圖來分析下
看明白了上面的過程,代碼就容易多了,我們看下
java
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
C語言
int maxDepth(struct TreeNode* root) {
if (root == NULL)
return 0;
return max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
int max(int left, int right) {
return left > right ? left : right;
}
C++
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
return max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
BFS:
除了遞歸,我們還可能想到的就是BFS(寬度優先搜索算法(又稱廣度優先搜索)),他的實現原理就是一層層遍歷,統計一下總共有多少層,我們來畫個圖分析一下。
一層一層往下走,統計總共有多少層,我們來看下代碼
java
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
int count = 0;
while (!stack.isEmpty()) {
int size = stack.size();
while (size-- > 0) {
TreeNode cur = stack.pop();
if (cur.left != null)
stack.addLast(cur.left);
if (cur.right != null)
stack.addLast(cur.right);
}
count++;
}
return count;
}
C++
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
int res = 0;
queue<TreeNode *>q;
q.push(root);
while (!q.empty()) {
++res;
for (int i = 0, n = q.size(); i < n; ++i) {
TreeNode * p = q.front();
q.pop();
if (p -> left != NULL)
q.push(p -> left);
if (p -> right != NULL)
q.push(p -> right);
}
}
return res;
}
DFS:
想到BFS我們一般會和DFS聯想到一起,DFS是深度優先搜索算法,我們先來看下代碼
java
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> value = new Stack<>();
stack.push(root);
value.push(1);
int max = 0;
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
int temp = value.pop();
max = Math.max(temp, max);
if (node.left != null) {
stack.push(node.left);
value.push(temp + 1);
}
if (node.right != null) {
stack.push(node.right);
value.push(temp + 1);
}
}
return max;
}
C++
public:
int maxDepth(TreeNode*root) {
if (root == NULL)
return 0;
stack<TreeNode *>nodeStack;
stack<int> value;
nodeStack.push(root);
value.push(1);
int max = 0;
while (!nodeStack.empty()) {
TreeNode * node = nodeStack.top();
nodeStack.pop();
int temp = value.top();
value.pop();
max = temp > max ? temp : max;
if (node -> left != NULL) {
nodeStack.push(node -> left);
value.push(temp + 1);
}
if (node -> right != NULL) {
nodeStack.push(node -> right);
value.push(temp + 1);
}
}
return max;
}
這裏使用了兩個棧,一個是存儲節點的,一個是存儲每個節點到根節點總共經過多少個節點(包含根節點和當前節點)。