//basic idea is that traveral the tree, while visiting current node, calculate the depth of the max prefect subtree with current node as the root. The depth of the final result subtree must be one of such depth(in fact, the maximum one).
class MaxPerfectSubtree{
private int maxDepth=0;//global var for current depth of the max prefect subtree with current node as its root,updated while doing postorder traversal
public int solution(TreeNode root){
postorder(root);//traversal the tree in a buttom-up style while updating the maxDepth
return (int)Math.pow(2,maxDepth+1)-1;//with the max depth, the max node count is trival.
}
private int postorder(TreeNode root){//returns the depth of the max prefect subtree with root as its root.
if(root==null)
return 0;//
int left=postorder(root.left);
int right=postorder(root.right);
int curDepth=1+Math.min(left,right);//max prefect subtree with root as its root
if(maxDepth<curDepth)
maxDepth=curCount;
return curDepth;
}
}
Примечание: просто чтобы продемонстрировать идею, нет грантополучателя, что он может запустить и дать правильный ответ.
Обновление просто найдено что помимо количества узлов также необходим обход по дереву, как показано в приведенной ссылке (который c означает, что дерево также требуется).
Таким образом, мы можем добавить глобальный TreeNode
переменная для записи узла root, соответствующего глобальной переменной maxDepth
.
А затем переупорядочить этот TreeNode в стиле верхней кнопки, с левой глубиной в качестве параметра функции обхода inorder, чтобы мы могли разбить, как только мы достигнем максимальной глубины.