Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
求二叉树深度,直接看代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxDepth(TreeNode* root) { 13 if(root == NULL) return 0; 14 _max = 1; 15 tranverse(root->left, 1); 16 tranverse(root->right, 1); 17 return _max; 18 } 19 void tranverse(TreeNode * node, int count) 20 { 21 if(node == NULL) 22 return; 23 else{ 24 if(count + 1 > _max) 25 _max = count + 1; 26 tranverse(node->left, count + 1); 27 tranverse(node->right, count + 1); 28 } 29 } 30 public: 31 int _max; 32 };
java版的如下所示,上面的递归写的还是太麻烦了,下面的简单很多哈:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int maxDepth(TreeNode root) { 12 if(root == null) 13 return 0; 14 return tranverse(root, 0); 15 } 16 17 public int tranverse(TreeNode root, int val){ 18 if(root.left == null && root.right == null) 19 return val+1; 20 int leftDep = 0, rightDep = 0; 21 if(root.left != null) 22 leftDep = tranverse(root.left, val + 1); 23 if(root.right != null) 24 rightDep = tranverse(root.right, val + 1); 25 return Math.max(leftDep, rightDep); 26 } 27 }