2018年2月13日 星期二

[104] Maximum Depth of Binary Tree

找binary tree的最高深度(?) 也就是height(嗎)
(各種問號 & 各種不精確XD)

Maximum Depth of Binary Tree
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    if (root == NULL)
        return 0;
//    if (root->left == NULL && root->right == NULL)
//        return 1;

    int left, right;
 //   if (root->left != NULL && root->right != NULL)
    {
        left = 1+maxDepth(root->left);      
        right = 1+maxDepth(root->right);
        return (left > right) ? left : right;
    }
#if 0
    if ((ptr = root->left) != NULL)
    {
        return 1 + maxDepth(ptr);
    }
     
    if ((ptr = root->right) != NULL)
    {
        return 1 + maxDepth(ptr);
    }

    return 1;
#endif
}
結果還多寫了很多判斷 囧
顯示為根本沒搞懂........唉

「20231213 更新」
稍微有比較懂了"使用遞迴去處理tree的問題"
但好像還是不是很漂亮?!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int height(struct TreeNode* root, int h)
{
if (root == NULL)
return h;
int left = height(root->left, h+1);
int right = height(root->right, h+1);
return (left> right)? left:right;
}

int maxDepth(struct TreeNode* root) {
return height(root, 0);
}

沒有留言:

張貼留言