leetcode 找树的左下角的值
题目描述:
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
java实现代码:
public int findBottomLeftValue(TreeNode root) {
int k=root.val;
while(root!=null){
//一层一层往下查找
k=root.val;
if(depth(root.left)<depth(root.right)){
root=root.right;
}
else{
root=root.left;
}
}
return k;
}
//获取二叉树的深度|高度
public int depth(TreeNode root){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
return Math.max(depth(root.left),depth(root.right))+1;
}
python实现代码:
class Solution(object):
def depth(self,root):
if not root:
return 0
if not root.left and not root.right:
return 1
left = self.depth(root.left)
right = self.depth(root.right)
return left+1 if left>right else right+1
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
k = root.val
while root:
k = root.val
if self.depth(root.left) < self.depth(root.right):
root = root.right
else:
root = root.left
return k
提交截图: