iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

刷題記錄與人生分享系列 第 20

DAY20 Maximum Depth of Binary Tree

  • 分享至 

  • xImage
  •  

題目:

https://leetcode.com/problems/maximum-depth-of-binary-tree/
求一個二元樹最大深度並回傳。

解題思路:

設置兩個變數計算左節點長度與右節點長度,利用遞迴特性尋訪將其對應變數加一,最後比較大小回傳。

C版本:

int maxDepth(struct TreeNode* root) {
    int l_num=0,r_num=0;
    if(root == NULL)
        return 0;
    if(root -> right == NULL && root -> left == NULL)
        return 1;
    if(root -> left != NULL)
    {
        l_num = 1+maxDepth(root -> left);
    }
    if(root -> right != NULL)
    {
        r_num = 1+maxDepth(root -> right);
    }
    return l_num > r_num ? (l_num) : (r_num);
}

Javascript版本:

var maxDepth = function(root) {
    var l_num=0,r_num=0;
    if(root == null)
        return 0;
    if(root.right == null && root.left == null)
        return 1;
    if(root.left != null)
    {
        l_num = 1+maxDepth(root.left);
    }
    if(root.right != null)
    {
        r_num = 1+maxDepth(root.right);
    }
    return l_num > r_num ? (l_num) : (r_num);
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

It’s not difficult to make a decision. It’s hard to put it into action and stick to it.
做一個決定,並不難,難的是付諸行動,並且堅持到底


上一篇
DAY19 Symmetric Tree
下一篇
DAY21 Convert Sorted Array to Binary Search Tree
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言