LeetCode 965. 单值二叉树
class Solution { public boolean isUnivalTree ( TreeNode root) { int val = root. val; return dfs ( root, val) ; } public boolean dfs ( TreeNode node, int val) { if ( node == null ) return true ; if ( node. val != val) return false ; return dfs ( node. left, val) && dfs ( node. right, val) ; }
}
LeetCode 257. 二叉树的所有路径
class Solution { public List < String > binaryTreePaths ( TreeNode root) { List < String > ans = new ArrayList < String > ( ) ; dfs ( ans, "" , root) ; return ans; } public void dfs ( List < String > ans, String path, TreeNode node) { if ( node != null ) { StringBuffer pathSB = new StringBuffer ( path) ; pathSB. append ( Integer . toString ( node. val) ) ; if ( node. left == null && node. right == null ) ans. add ( pathSB. toString ( ) ) ; else { pathSB. append ( "->" ) ; dfs ( ans, pathSB. toString ( ) , node. left) ; dfs ( ans, pathSB. toString ( ) , node. right) ; } } }
}
LeetCode 113. 路经总和II
class Solution { List < List < Integer > > ans = new LinkedList < List < Integer > > ( ) ; Deque < Integer > path = new LinkedList < Integer > ( ) ; public List < List < Integer > > pathSum ( TreeNode root, int targetSum) { if ( root == null ) return ans; dfs ( root, targetSum) ; return ans; } public void dfs ( TreeNode node, int targetSum) { if ( node == null ) return ; path. offerLast ( node. val) ; targetSum -= node. val; if ( node. left == null && node. right == null && targetSum == 0 ) ans. add ( new LinkedList < Integer > ( path) ) ; dfs ( node. left, targetSum) ; dfs ( node. right, targetSum) ; path. pollLast ( ) ; }
}
LeetCode 563. 二叉树的坡度
class Solution { int ans; public int findTilt ( TreeNode root) { ans = 0 ; dfs ( root) ; return ans; } public int dfs ( TreeNode node) { if ( node == null ) return 0 ; int left_sum = dfs ( node. left) ; int right_sum = dfs ( node. right) ; ans += Math . abs ( left_sum - right_sum) ; return left_sum + right_sum + node. val; }
}
LeetCode 687. 最长同值路径
class Solution { int ans; public int longestUnivaluePath ( TreeNode root) { ans = 0 ; if ( root == null ) return 0 ; dfs ( root) ; return ans; } public int dfs ( TreeNode node) { if ( node == null ) return 0 ; int left = dfs ( node. left) ; int right = dfs ( node. right) ; if ( node. left != null && node. left. val == node. val) left = left + 1 ; else left = 0 ; if ( node. right != null && node. right. val == node. val) right = right + 1 ; else right = 0 ; ans = Math . max ( ans, left+ right) ; return Math . max ( left, right) ; }
}
LeetCode 124. 二叉树中的最大路径和
class Solution { int ans; public int maxPathSum ( TreeNode root) { ans = Integer . MIN_VALUE ; dfs ( root) ; return ans; } public int dfs ( TreeNode node) { if ( node == null ) return 0 ; int left = Math . max ( dfs ( node. left) , 0 ) ; int right = Math . max ( dfs ( node. right) , 0 ) ; ans = Math . max ( ans, node. val+ left+ right) ; return node. val + Math . max ( left, right) ; }
}