Leetcode:Maximum Depth of Binary Tree
Maximum Depth of Binary Tree
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.
Answer
這個題目學習的是關於 Node 的連結和遞迴應用,所以不考慮 Node 連結到底有多深,只考慮回傳累加,而最深的累加必定最多。Javascript
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/var maxDepth = function(root){
var x, y;
if(!root)
return 0;
x = maxDepth(root.left);
y = maxDepth(root.right);
return (x>=y) ? (x+1) : (y+1);
}
//Min:140ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
然而在上方算法列數非常精簡,處理速度也不錯,但是我想嘗試另一種寫法,並看看處理速度是否有差異。
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
var maxDepth = function(root){
var x, y;
if(root){
x = maxDepth(root.left);
y = maxDepth(root.right);
}else{
return 0;
}
return (x>=y) ? (x+1) : (y+1);
}
//Min:128ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/而這個結果告訴我們了差異性其實不小,可能是因為第二個算法不需要多運算 NOT root ,而加快了整個程式的處理。
之後我嘗試了 python 和 c 的寫法,而取得結構下的資料有點忘記要如何操作,於是上網 Google 了一下操作方法,在 C 底下是用 -> ,python 則跟 javascript 操作差不多,然而一直出現 function 錯誤,我起初也不知道甚麼原因,直到看了其他範例才了解執行同函數但非在最外層的遞迴用 self. 才可以執行。
Python
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/class Solution(object):
def maxDepth(self, root):
if (root == None):
return 0
x = self.maxDepth(root.left)
y = self.maxDepth(root.right)
if (x>=y):
return (x+1)
return (y+1)
#Min:60ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
C
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/int maxDepth(struct TreeNode* root){
int x, y;
if(root){
x = maxDepth(root->left);
y = maxDepth(root->right);
}else{
return 0;
}
return (x >= y) ? (x+1) : (y+1);
}
//Min:4ms
留言
張貼留言