https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/description/
這道題是智能從上下往下的炎疆,我們想如果子樹(shù)有一個(gè)長(zhǎng)度求好后」眩看父親的時(shí)候形入,如果父親是其中一個(gè)孩子的VAL-1,那么就可以嘗試把父親接進(jìn)去缝左,并且嘗試更新MAXLEN的值亿遂。同時(shí)RETURN 新的長(zhǎng)度給父親的父親
這樣就有了遞歸子結(jié)構(gòu)了。
那么遞歸終止條件在哪渺杉? 就是葉子節(jié)點(diǎn)蛇数,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é)點(diǎn)開(kāi)始往下走。傳的參數(shù)里維護(hù)一個(gè)長(zhǎng)度倚评,還需要孩子的能練起來(lái)的TARGER的VAL浦徊,如果孩子的VAL可以滿足,就更新長(zhǎng)度天梧。
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;
}
}