二叉树深度(最大和最小)

来源:互联网 发布:巨人网络手游官网注册 编辑:程序博客网 时间:2024/05/19 14:16
/**最大深度 * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int maxDepth(struct TreeNode* root) {       if (!root) return 0;  //空树返回0        int lh = maxDepth(root->left);          int rh = maxDepth(root->right);          return lh > rh ? lh + 1 : rh + 1;      }

二叉树类的问题都会考虑采用递归的方式进行求解,因为二叉树本身就是递归定义的。

//最小深度
int minDepth(TreeNode *root)       {         if (!root) return 0;         int hl = minDepth(root->left);         int hr = minDepth(root->right);         if (!hl) return hr + 1;         if (!hr) return hl + 1;         return hl < hr ? hl + 1 : hr + 1;      }  

最小深度: 从根节点开始到叶子节点结束的最短路径上的节点数。采用递归方案的解法:

1. 空树最小深度是0.    

2. 左子树空: 右子树最小深度+ 1 

3. 右子树空: 左子树最小深度 + 1

4. min(左子树最小深度,右子树最小深度) + 1



0 0