您的位置:首页 > 其它

二叉树的最大深度

2015-08-01 16:13 393 查看
1、二叉树的最大深度问题:

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root == nullptr) {
return 0;//这个就已经包括所有情况了,包括到达叶子节点以及没有根节点的情况
}
int left = maxDepth(root -> left);
int right = maxDepth(root -> right);
return (left > right) ? left + 1 : right +1 ;
}
};
2、求二叉树两个点的最近公共祖先(包括他自己)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if (root == nullptr || A == root || B == root) {//对递归基的理解不透彻
return root;
}

TreeNode *left = lowestCommonAncestor(root -> left, A, B);
TreeNode *right = lowestCommonAncestor(root -> right, A, B);

if (left != nullptr && right != nullptr) {
return root;
}
if (right != nullptr) {
return right;
}
if (left != nullptr) {
return left;
}
return nullptr;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: