https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/description/
image.png
這道題是智能從上下往下的,我們想如果子樹有一個長度求好后。看父親的時候,如果父親是其中一個孩子的VAL-1,那么就可以嘗試把父親接進(jìn)去,并且嘗試更新MAXLEN的值。同時RETURN 新的長度給父親的父親
這樣就有了遞歸子結(jié)構(gòu)了。
那么遞歸終止條件在哪? 就是葉子節(jié)點,return1就好。
int max = 0;
public int longestConsecutive(TreeNode root) {
help(root);
return max;
}
private int help(TreeNode cur) {
if(cur == null) return 0;
int left = help(cur.left);
int right = help(cur.right);
int me = 1;
if(cur.left!=null && cur.val == cur.left.val-1){
me = 1+left;
}
if(cur.right!=null && cur.val == cur.right.val-1){
me = Math.max(me,1+right);
}
max = Math.max(me,max);
return me;
}
另外一種思考方式,就是正著思考,我們從父節(jié)點開始往下走。傳的參數(shù)里維護(hù)一個長度,還需要孩子的能練起來的TARGER的VAL,如果孩子的VAL可以滿足,就更新長度。
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
Stack<Cmd> st = new Stack<>();
st.push(new Cmd(root.val,0,root));
int max = 0;
while(!st.isEmpty()){
Cmd cmd = st.pop();
if(cmd.cur == null) continue;
int val = cmd.val;
if(cmd.cur.val == cmd.tar){
val++;
}else{
val = 1;
}
max = Math.max(val,max);
st.push(new Cmd(cmd.cur.val+1,val,cmd.cur.right));
st.push(new Cmd(cmd.cur.val+1,val,cmd.cur.left));
}
return max;
}
class Cmd{
//int op;//0 is visit, 1 is do
TreeNode cur;
int tar;
int val;
public Cmd(int tar,int val,TreeNode cur){
this.tar = tar;
this.val = val;
this.cur = cur;
}
}