我自己写的divide&conquer
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ public int maxDepth(TreeNode root) { // write your code here if (root == null) { return 0; //? } int result = divide(root); return result; } private int divide(TreeNode root) { if (root == null) { return 0; } int re1 = divide(root.left); int re2 = divide(root.right); if (re1 >= re2) { return re1 + 1; } else { return re2 +1; } } }
九章
// Version 1: Divide Conquer public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); return Math.max(left, right) + 1; } }
递归老写错,摊手╮(╯-╰)╭
正确的:我抄的答案
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ private int result; public int maxDepth(TreeNode root) { // write your code here result = 0; //这里不能写int result 不能重新定义 traverse(root, 1);//传入1不是0 return result; } private void traverse(TreeNode root, int curr) { if (root == null) { return ; } if (curr > result) { //先写这个 result = curr; } traverse(root.left, curr + 1); traverse(root.right, curr + 1); } }
九章
// version 2: Traverse /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ private int depth; public int maxDepth(TreeNode root) { depth = 0; helper(root, 1); return depth; } private void helper(TreeNode node, int curtDepth) { if (node == null) { return; } if (curtDepth > depth) { depth = curtDepth; } helper(node.left, curtDepth + 1); helper(node.right, curtDepth + 1); } }
错的
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int maxDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0; //?
}
int result = 0;
traverse(root, result);
return result;
}
private void traverse(TreeNode root, int result) {
if (root == null) {
return;
}
int re1 = 0;
int re2 = 0;
traverse(root.left, re1);
traverse(root.right, re2);
if (re1 >= re2) {
result = re1 + 1;
} else {
result = re2 +1;
}
}
}