while (p || !stk.empty()) { if (p) { stk.push(p); p = p->left; } else { p = stk.top(); if (p->right && last != p->right) { p = p->right; } else { // visit p
classSolution { int ans; intdepth(TreeNode *rt) { if (rt == NULL) { return0; // 访问到空节点了,返回0 } int L = depth(rt->left); // 左儿子为根的子树的深度 int R = depth(rt->right); // 右儿子为根的子树的深度 ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans returnmax(L, R) + 1; // 返回该节点为根的子树的深度 }
public: intdiameterOfBinaryTree(TreeNode *root) { ans = 1; depth(root); return ans - 1; } };