513. 找树左下角的值
思路:
- 离不开二叉树的遍历
- 寻找叶子结点,且深度最深
public class Solution {
private int maxDepth = Int32.MinValue;
private int result;
public int FindBottomLeftValue(TreeNode root) {
FindDeepestLeefNode(root,0);
return result;
}
public void FindDeepestLeefNode(TreeNode node, int depth)
{
//depth++;
if(node.left == null && node.right == null)
{
if(depth > maxDepth){
maxDepth = depth;
result = node.val;
}
return;
}
if(node.left != null)
{
depth++;
FindDeepestLeefNode(node.left, depth);
depth--;
}
if(node.right != null)
{
depth++;
FindDeepestLeefNode(node.right, depth);
depth--;
}
}
}
Q: 为什么如下code不work?
A: depth为值变量,不能再递归中传递,得用一个全局的变量。
public class Solution {
private int maxDepth = Int32.MinValue;
//private int depth = 0;
private int result;
public int FindBottomLeftValue(TreeNode root) {
FindDeepestLeefNode(root,0);
return result;
}
public void FindDeepestLeefNode(TreeNode node, int depth)
{
depth++;
if(node.left == null && node.right == null)
{
if(depth > maxDepth){
maxDepth = depth;
result = node.val;
}
return;
}
if(node.left != null)
{
FindDeepestLeefNode(node.left, depth);
depth--;
}
if(node.right != null)
{
FindDeepestLeefNode(node.right,depth);
depth--;
}
}
}
112 路径总和
思路
- 离不开二叉树的遍历
- 遍历过程中 求和
public class Solution {
public bool HasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
return hasPath(root,root.val,targetSum);
}
public bool hasPath(TreeNode node, int sum, int target)
{
if(node.left == null && node.right == null)
{
if(sum == target) return true;
return false;
}
if(node.left != null)
{
sum+=node.left.val;
if(hasPath(node.left, sum, target)) return true;
sum-=node.left.val;
}
if(node.right != null)
{
sum+=node.right.val;
if(hasPath(node.right, sum, target)) return true;
sum-=node.right.val;
}
return false;
}
}
113.路径总和II
public class Solution {
public IList<IList<int>> PathSum(TreeNode root, int targetSum) {
IList<IList<int>> result = new List<IList<int>>();
if(root == null) return result;
List<int> path = new List<int>();
getPath(root,targetSum,path,result);
return result;
}
public void getPath(TreeNode node, int targetSum, List<int> path, IList<IList<int>> result)
{
path.Add(node.val);
if(node.left == null && node.right == null)
{
int sum = 0;
List<int> tmp = new List<int>();
for(int i = 0;i < path.Count;i++)
{
sum+=path[i];
tmp.Add(path[i]);
}
if(sum == targetSum)
{
result.Add(tmp);//耽误了很长时间,不能直接加path,path为引用对象
}
}
if(node.left != null)
{
getPath(node.left, targetSum, path, result);
path.RemoveAt(path.Count - 1);
}
if(node.right != null)
{
getPath(node.right, targetSum, path, result);
path.RemoveAt(path.Count - 1);
}
}
}