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.
遞迴求解
int maxDepth(TreeNode *root){ return root? 1+max(maxDepth(root->left), maxDepth(root->right)) : 0; }
非遞迴求解
struct Node{ TreeNode *node; int depth; Node(TreeNode *a = NULL , int d = 0):node(a), depth(d); }; int maxDepth1(TreeNode *root){ if(root == NULL) return 0; queue<Node> que; Node rootNode(root,1); que.push(rootNode); int res = 0; while(!que.empty()){ Node p = que.front();que.pop(); res = p.depth; if(p.node->left) que.push(Node(p.node->left,p.depth+1)); if(p.node->right ) que.push(Node(p.node->right,p.depth+1)); } return res; }