代码随想录day18
此题我们采用层序遍历的方法。返回最底层的左边值即是我们所求的值
class Solution {
public int findBottomLeftValue ( TreeNode root) {
LinkedList < TreeNode > list = new LinkedList < > ( ) ;
list. offer ( root) ;
int ans = 0 ;
while ( ! list. isEmpty ( ) ) {
int size = list. size ( ) ;
for ( int i = 0 ; i < size ; i++ ) {
TreeNode node = list. poll ( ) ;
if ( i == 0 ) {
ans = node. val;
}
if ( node. left != null ) {
list. offer ( node. left) ;
}
if ( node. right != null ) {
list. offer ( node. right) ;
}
}
}
return ans;
}
}
此题使用一个递归的思想,每遇到一个节点就另目标值减去此节点的值,遇到叶子节点时进行判断是否为零,为零则符合题意返回true
class Solution {
public boolean hasPathSum ( TreeNode root, int targetSum) {
if ( root == null ) {
return false ;
}
boolean right = false ;
boolean left = false ;
targetSum -= root. val;
if ( root. left == null && root. right == null ) {
return targetSum == 0 ;
}
if ( root. left != null ) {
left = hasPathSum ( root. left, targetSum) ;
}
if ( root. right != null ) {
right = hasPathSum ( root. right, targetSum) ;
}
if ( left || right) return true ;
return false ;
}
}
class Solution {
List < List < Integer > > ans = new ArrayList < > ( ) ;
LinkedList < Integer > path = new LinkedList < > ( ) ;
public List < List < Integer > > pathSum ( TreeNode root, int targetSum) {
if ( root == null ) {
return ans;
}
path ( root , targetSum) ;
return ans;
}
void path ( TreeNode root , int targetSum) {
path. add ( root. val) ;
targetSum -= root. val;
if ( targetSum == 0 && root. left == null && root. right == null ) {
ans. add ( new ArrayList ( path) ) ;
}
if ( root. left != null ) {
path ( root. left, targetSum) ;
path. removeLast ( ) ;
}
if ( root. right != null ) {
path ( root. right, targetSum) ;
path. removeLast ( ) ;
}
}
}
后序数组的最后一位元素就是我们的根节点 根据根节点将中序数组分为左右两部分 左部分就是我们的根节点的左子树部分,另其反复执行上述两个程序(递归) 右子树同左子树 由于整个过程中我们的所有的计数均从0开始,所以索引下标取不到length的值,故使用左闭右开
class Solution {
Map < Integer , Integer > map;
public TreeNode buildTree ( int [ ] inorder, int [ ] postorder) {
map = new HashMap < > ( ) ;
for ( int i = 0 ; i < inorder. length ; i++ ) {
map. put ( inorder[ i] , i) ;
}
return tree ( inorder , 0 , inorder. length , postorder , 0 , postorder. length) ;
}
public TreeNode tree ( int [ ] inorder, int inBegin, int inEnd,
int [ ] postorder, int postBegin, int postEnd) {
if ( inBegin >= inEnd || postBegin >= postEnd) {
return null ;
}
int rootIndex = map. get ( postorder[ postEnd - 1 ] ) ;
TreeNode root = new TreeNode ( inorder[ rootIndex] ) ;
int len = rootIndex - inBegin;
root. left = tree ( inorder, inBegin, rootIndex,
postorder, postBegin, postBegin+ len) ;
root. right = tree ( inorder, rootIndex+ 1 , inEnd,
postorder, postBegin+ len, postEnd- 1 ) ;
return root;
}
}