謝謝@n.m。爲您的評論。我已經使用您的輸入實施瞭解決方案。
邏輯:
的基本邏輯是一個節點的isRoman
字段設置爲false
,即使一個節點的後代(假設盛大隆重的孩子)不是羅馬。這意味着即使節點滿足屬性(左右後裔最多5個),但是如果其左右子樹的isRoman
是false
,那麼當前節點的isRoman
也將是false
。
/*
* public class TreeNode {
* int val;
* int size; //stores the number of descendants including itself
* boolean isRoman; // is true when this node is roman and all its descendants are roman,
* //false even when a grand grand child node of this node is not roman.
* TreeNode left;
* TreeNode right;
* }
*/
public static void roman(TreeNode root, List<TreeNode> lst){
if(root == null)
return;
if(root.left == null && root.right == null){
root.size = 1;
root.isRoman = true;
return;
}
int left = 0;
int right = 0;
boolean isLeftRoman = false;
boolean isRightRoman = false;
if(root.left != null) {
roman(root.left,lst);
left = root.left.size;
isLeftRoman = root.left.isRoman;
}
if(root.right != null) {
roman(root.right,lst);
right = root.right.size;
isRightRoman = root.right.isRoman;
}
//if the current node is roman and all it's descendants are roman, update isRoman to true
if(Math.abs(left-right) <= 5 && isLeftRoman && isRightRoman)
root.isRoman = true;
else
root.isRoman = false;
//update the current node's size
root.size = left+right+1;
//add the node to list which is not roman but all its descendants are roman
if(Math.abs(left-right) > 5 && isLeftRoman && isRightRoman)
lst.add(root);
}
這種自下而上的方法被稱爲後序。嘗試在每一步計算兩件事情,例如子樹中的節點數量以及所有節點是否爲羅馬。 –
我與@n.m。 - 每個節點都是一個額外的'int'和一個額外的'bool',這可能是可以接受的... –