Leetcode题解:513. Find Bottom Left Tree Value
来源:互联网 发布:苹果六怎么备份数据 编辑:程序博客网 时间:2024/04/26 16:03
难度:Medium 类型:树
513. Find Bottom Left Tree Value
题目
Given a binary tree, find the leftmost value in the last row of the tree.
概述
给定二叉树,找出其最底层的最左边元素
Input:
1 / \ 2 3 / / \4 5 6 / 7
Output:
7
分析
其实所谓最底层节点,即为深度最深的节点,且该节点一定是叶子节点。所以只要用DFS遍历到最深的节点,这里可以采用前序遍历的方法,由于会先访问本节点的左子树,所以找到第一个深度最深的叶子节点即为最底层最左边节点。同样的,若问题求最底层最右边节点,只需要调换前序遍历左右子树遍历顺序先访问右子树即可。
当然也可以使用BFS的方法,从右子树节点开始加入队列,访问的队列中的最后一个节点就是所需要求得的最底层最左边节点。
参考代码给出的是前序遍历的方法。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int curdepth = -1, maxdepth=-1; int ans; int findBottomLeftValue(TreeNode* root) { curdepth++; if(root->left==NULL && root->right==NULL){ if(curdepth>maxdepth){ ans = root->val; maxdepth = curdepth; } } if(root->left!=NULL) findBottomLeftValue(root->left); if(root->right!=NULL) findBottomLeftValue(root->right); curdepth--; return ans; }};
0 0
- Leetcode题解:513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- [leetcode]513. Find Bottom Left Tree Value
- [leetcode] 513. Find Bottom Left Tree Value
- 【LeetCode】513. Find Bottom Left Tree Value
- Leetcode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- 【leetcode】 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value | LeetCode
- leetcode-513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- leetcode 513. Find Bottom Left Tree Value
- leetcode 513. Find Bottom Left Tree Value
- [leetcode]513. Find Bottom Left Tree Value
- Leetcode 513. Find Bottom Left Tree Value
- leetcode 513. Find Bottom Left Tree Value
- [LeetCode] 513. Find Bottom Left Tree Value
- 用Criteria进行模糊查询实现简单的搜索功能
- CodeForces
- leetcode---Product of Array Except Self
- 向上转型和向下转型
- 有向图的欧拉道路 UVA
- Leetcode题解:513. Find Bottom Left Tree Value
- RHEL6.5 LVM硬盘管理
- leetcode508
- 1091. Acute Stroke (30)[bfs广度优先搜索+种子填充]
- 64位MinGW和MSYS的安装
- java集合
- 数据挖掘---关联规则---ECLAT算法
- 启动关闭一个网络接口时的连带效应
- android之MediaPlayer 和SoundPool