力扣104 二叉树最大深度 普通递归遍历
int depth = 0 ;
int maxDepth = 0 ;
public int maxDepth ( TreeNode root) {
traverse ( root) ;
return maxDepth;
}
public void traverse ( TreeNode root) {
if ( root == null ) {
return ;
}
depth++ ;
if ( root. right == null && root. left == null ) {
maxDepth = maxDepth> depth? maxDepth: depth;
depth-- ;
return ;
}
traverse ( root. left) ;
traverse ( root. right) ;
depth-- ;
return ;
}
力扣 104 递归遍历2
int depth = 0 ;
int maxDepth = 0 ;
public int maxDepth ( TreeNode root) {
maxDepth = traverse ( root) ;
return maxDepth;
}
public int traverse ( TreeNode root) {
if ( root == null ) {
return 0 ;
}
int left = traverse ( root. left) ;
int right = traverse ( root. right) ;
maxDepth = left>= right? left: right;
maxDepth++ ;
return maxDepth;
}
二叉树求前序遍历结果
public static void PreOrderTraverse ( TreeNode root) {
if ( root != null ) {
linkedListPreOrder. add ( root. val) ;
PreOrderTraverse ( root. left) ;
PreOrderTraverse ( root. right) ;
} else {
return ;
}
}
二叉树求 每个节点所在层数与每个节点的左右子树上的节点总数
public static int traverseRootCount ( TreeNode root) {
if ( root == null ) {
return 0 ;
}
int leftCount = traverseRootCount ( root. left) ;
int rightCount = traverseRootCount ( root. right) ;
System . out. printf ( "当前节点为%d, 它的左子树有%d个节点, 右子树有%d个节点\n" , root. val, leftCount, rightCount) ;
return leftCount + rightCount + 1 ;
}
public static int traverseRootCount ( TreeNode root, int level) {
if ( root == null ) {
return 0 ;
}
level++ ;
int leftCount = traverseRootCount ( root. left, level) ;
int rightCount = traverseRootCount ( root. right, level) ;
System . out. printf ( "当前节点为%d, 位于第%d层, 它的左子树有%d个节点, 右子树有%d个节点\n" ,
root. val, level, leftCount, rightCount) ;
return leftCount + rightCount + 1 ;
}
力扣 543 二叉树的直径
int max = 0 ;
public int diameterOfBinaryTree ( TreeNode root) {
if ( root== null ) {
return 0 ;
}
int leftMax = depthMax ( root. left) ;
int rightMax = depthMax ( root. right) ;
max = Math . max ( max, leftMax+ rightMax) ;
return max;
}
public int depthMax ( TreeNode root) {
if ( root == null ) {
return 0 ;
}
int left = depthMax ( root. left) + 1 ;
int right = depthMax ( root. right) + 1 ;
max = Math . max ( max, left- 1 + right- 1 ) ;
return Math . max ( left, right) ;
}