二叉树题目的递归解法
程序员文章站
2024-03-18 22:12:28
...
递归是解决二叉树题目最方便的方法之一,递归一般分为两种情况,”top-down“(从上至下)和“bottom-top”(从下至上),让我们通过一道简单的例题来了解这两种方式。
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
"top-down" solution
通过根节点给子节点传递状态,函数需要有一个参数来记录状态变化,在叶结点处判断结果
int answer;
void maxDepth(struct TreeNode* root, int depth){
if(!root) return;
//到叶节点(终点状态),更新结果
if (!root->left && !root->right) {
answer = max(answer, depth);
}
//向两个子节点传递状态
maxDepth(root->left,depth+1);
maxDepth(root->right,depth+1);
}
"bottom to top" solution
一直向下递归,从下至上返回结果,在根节点处判断结果
int maxDepth(struct TreeNode* root){
if(root==NULL) return 0;
//通过左右子树确定根节点的状态
return max(maxDepth(root->left),maxDepth(root->right))+1;
}