leetcode 513. Find Bottom Left Tree Value 最左边的值 + 一个简单的DFS深度优先遍历
2018-02-08 09:38
633 查看
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
Output:
1
Example 2:
Input:
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
题意很简单,直接做DFS深度优先遍历即可,在遍历的时候作比较即可
代码如下:
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深度优先遍历即可,在遍历的时候作比较即可
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <cmath> using namespace std; /* struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { if (root == NULL) return 0; int maxDepth = 0 , res = root->val; getAll(root,maxDepth,0,res); return res; } void getAll(TreeNode* root, int& maxDepth, int depth,int& res) { if (root == NULL) return; else { getAll(root->left, maxDepth, depth + 1, res); getAll(root->right, maxDepth, depth + 1, res); if (depth > maxDepth) { maxDepth = depth; res = root->val; } return; } } };
相关文章推荐
- leetcode 508. Most Frequent Subtree Sum 子树和 + 一个简单的DFS深度优先遍历的做法
- leetcode 491. Increasing Subsequences所有的递增序列 + 一个典型的深度优先遍历DFS的做法
- leetcode 473. Matchsticks to Square 火柴摆正方形 + 一个经典深度优先遍历DFS的应用
- leetcode 464. Can I Win 100相加游戏 + 一个十分棒的深度优先遍历DFS的做法
- leetcode 329. Longest Increasing Path in a Matrix 矩阵中寻找最长递增序列 + 一个典型的深度优先遍历DFS的做法
- leetcode 650. 2 Keys Keyboard 最小复制粘贴次数 + 深度优先遍历DFS
- leetcode 547. Friend Circles 寻找图的环的数量 + 典型的深度优先遍历DFS
- leetcode 397. Integer Replacement 二分查找 + 深度优先遍历DFS
- leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
- leetcode 417. Pacific Atlantic Water Flow可以到达两边的点+经典DFS深度优先遍历做法
- leetcode 257. Binary Tree Paths 深度优先遍历DFS
- leetcode 132. Palindrome Partitioning II 回文子串 + 深度优先遍历DFS(超时) + 动态规划DP + 这道题需要认真学习
- leetcode 623. Add One Row to Tree二叉树添加指定深度元素+ 深度优先遍历DFS
- leetcode 526. Beautiful Arrangement 递归实现全排列 + 经典深度优先遍历DFS做法
- leetcode 530. Minimum Absolute Difference in 二叉搜索树的中序遍历 + 深度优先遍历DFS
- leetcode 606. Construct String from Binary Tree 前序遍历 + 深度优先遍历DFS
- leetcode 113. Path Sum II DFS深度优先遍历
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- leetcode 543. Diameter of Binary Tree 最长树的片段 + 深度优先遍历DFS
- leetcode 392. Is Subsequence 子序列判断 深度优先遍历DFS + 一个很简单的循环