总结先放在前面:
无
解答二叉树时的一些小技巧与注意点:
无
题目实战
1.NO.404. 左叶子之和
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
int sumLeft=0;
public int SumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
if(root.left!=null){
if(root.left.left==null&&root.left.right==null){
return sumLeft+root.left.val+SumOfLeftLeaves(root.right);
}
}
return sumLeft+SumOfLeftLeaves(root.left)+SumOfLeftLeaves(root.right);
}
}
2.NO.112. 路径总和
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool HasPathSum(TreeNode root, int targetSum) {
return myHasPathSum(root,0,targetSum);
}
public bool myHasPathSum(TreeNode root ,int curSum ,int targetSum){
if(root!=null){
curSum=curSum+root.val;
if(root.left==null&&root.right==null){
return curSum==targetSum?true:false;
}
return myHasPathSum(root.left,curSum,targetSum)||myHasPathSum(root.right,curSum,targetSum);
}
return false;
}
}
3.NO.113.路径总和II
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
List<IList<int>> ans = new List<IList<int>>();