java代码实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
int leftDepth=TreeDepth(root.left);
int rightDepth=TreeDepth(root.right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
}
Python代码实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if(not pRoot):
return 0
ld = self.TreeDepth(pRoot.left)
rd = self.TreeDepth(pRoot.right)
return max(ld+1,rd+1)
几点感想
(1)许久不写代码,java中的.运算符和C++中->运算符混用,我真是太蠢了!
(2)java判断对象为空(通过判断对象引用是否为空)与Python有区别(通过判断对象引用是否为None),又混用了,注意Python中None和NULL的区别。
(3)Python中没有冒号表达式,但可以通过if else的特殊形式:为真的结果 if 条件 else 为假的结果。