LeetCode---513. Find Bottom Left Tree Value(DFS)
来源:互联网 发布:做淘宝需要什么设备 编辑:程序博客网 时间:2024/06/11 15:45
Find Bottom Left Tree Value(Depth-first-search)
Given a binary tree, find the leftmost value in the last row of the tree
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1 / \ 2 3 / / \4 5 6 / 7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
采用深度优先算法(DFS)
基本思想:
搜索节点时,要记录下树的深度,时时更新leftval,比较Dep和dep,确保leftval是最后一排的最左边的值。
/** * 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 findBottomLeftValue(TreeNode* root) { int leftval = 0, Dep = -1; //Dep 是整棵树的深度 DFS(root, leftval, Dep, 0);//根节点所处的位置,深度为0 return leftval; }private: void DFS(TreeNode* root, int&leftval, int&Dep, int dep){ //dep是该节点所处的深度 if(dep>Dep){ leftval = root->val; Dep = dep; } if(root->left){//左节点非空 DFS(root->left, leftval, Dep, dep+1); } if(root->right){//右节点非空 DFS(root->right, leftval, Dep, dep+1); } }};
test:
Input:
[5,4,7,3,6,2,null,-1,8,9]
Output:
-1
阅读全文
0 0
- LeetCode---513. Find Bottom Left Tree Value(DFS)
- [DFS]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
- Java环境的搭建
- 简单认识TCP/IP传输协议
- 译-设计模式-结构模式之Decorator
- 操作系统学习笔记(1) 进程
- 【笔记】《WebGL编程指南》学习-第3章绘制和变换三角形(1-绘制多个点)
- LeetCode---513. Find Bottom Left Tree Value(DFS)
- Java设计模式——桥接模式(Bridge Pattern)
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛——Minimum(I题)
- 写程序学ML:决策树算法原理及实现(一)
- 1073. 多选题常见计分法(20)
- LODOP WEB项目打印功能
- 多线程(二)--同步及死锁
- ST下载提示No Cortex-M SW Device Found
- Go语言开发常见陷阱,你遇到过几个?