【对递归的理解】Maximum Depth of Binary Tree
2015-03-23 15:49
561 查看
【题目描述】
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.
求一棵二叉树的最大深度,利用递归实现。代码如下:
以一个非常简单的二叉树作为示例,第一次进入递归函数时,用单箭头表示。返回时用双箭头表示并用ret加上返回值返回。具体调用过程见下图:
总结:
1. 要有能使递归终止的条件,否则将一直执行下去;
2.每一层次的递归函数调用都会有本层次递归函数的局部变量,再遇到返回条件时反方向向前返回值。
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.
求一棵二叉树的最大深度,利用递归实现。代码如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if(root == NULL){ return 0; } int leftMax = maxDepth(root->left); int rightMax = maxDepth(root->right); if(leftMax >= rightMax){ return leftMax+1; } else{ return rightMax+1; } } };递归程序调用过程分析如下:
以一个非常简单的二叉树作为示例,第一次进入递归函数时,用单箭头表示。返回时用双箭头表示并用ret加上返回值返回。具体调用过程见下图:
总结:
1. 要有能使递归终止的条件,否则将一直执行下去;
2.每一层次的递归函数调用都会有本层次递归函数的局部变量,再遇到返回条件时反方向向前返回值。
相关文章推荐
- 【二叉树的递归】02二叉树的最大深度【Maximum Depth of Binary Tree】
- 5.4.2—二叉树的递归—Maximum Depth of Binary Tree
- leetcode_104题——Maximum Depth of Binary Tree (二叉树,递归,队列,还有递归没想出来)
- [LeetCode]Maximum Depth of Binary Tree(递归和层序遍历解法)@python
- LeetCode maximumDepthOfBinaryTree递归,迭代解法
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- Leetcode: Maximum Depth of Binary Tree 理解分析
- 【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归
- 30.leetcode题目104: Maximum Depth of Binary Tree(递归,深度优先)
- Maximum Depth of Binary Tree
- Minimum(Maximum) Depth of Binary Tree
- Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- Maximum Depth of binary tree
- Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree