这道题的递归比迭代要难写,recursion是一道树上带回溯,iteration几乎套层次遍历即可。
1.递归写法
说白了就是要找到深度最大的叶子节点
?如何保证深度最大的就是最左的?——使用前序遍历
?为什么使用的是前序遍历而不是更倾向于左边的中序遍历
前序遍历中最先访问到的就是最左边的叶子节点。
我们对每个结点的操作是:如果他是叶子节点,则更新深度,否则就继续往下走。
class Solution {
private int maxDeep = -1;
private int maxLeftValue = 0;
public int findBottomLeftValue(TreeNode root) {
traversal(root, 0);
return maxLeftValue;
}
private void traversal(TreeNode root, int depth) {
if(root.left == null && root.right == null) {
if(depth > maxDeep) {
maxDeep = depth;
maxLeftValue = root.val;
}
}
if(root.left != null) traversal(root.left, depth+1);
if(root.right != null) traversal(root.right, depth+1);
}
}
2.层次遍历写法
用一个值来表示每一层最左边的值即可,遍历结束该值保存的就是最后一层最左边的值,即题目所求
class Solution {
public int findBottomLeftValue(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int ans = 0;
while(!q.isEmpty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode node = q.poll();
if(i == 0) ans = node.val;
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
}
}
return ans;
}
}
原文地址:https://www.cnblogs.com/huangming-zzz/p/15971152.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。