Posted onEdited onInLeetCodeDisqus: Symbols count in article: 2.3kReading time ≈2 mins.
O(h) time O(h) space 递归版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p){ if (!root) return root; if (root->val <= p->val) return inorderSuccessor(root->right, p); auto l = inorderSuccessor(root->left, p); return l ? l : root; } };
循环版 O(h) time O(1) space 比p大的第一个节点要不是p的父节点(p是其父节点的左子)要不在p的右子树上,从root开始往下找,如果当前的root比p大,说明这个点有可能是p的父节点,即有可能是最终解,先存下来继续往下找,如果当前的root不比p大,说明这个点肯定不是最终解,最终解要不已经被存下来(之前的最近的父节点)要不就还在右子树上,则继续沿着右子树往下找,如果在右子树上找到了符合要求的(比p大的)节点,则存下来更新res,直到找到叶节点为止,复杂度就是树高