298. Binary Tree Longest Consecutive Sequence

https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/description/

image.png

这道题是智能从上下往下的,我们想如果子树有一个长度求好后。看父亲的时候,如果父亲是其中一个孩子的VAL-1,那么就可以尝试把父亲接进去,并且尝试更新MAXLEN的值。同时RETURN 新的长度给父亲的父亲
这样就有了递归子结构了。
那么递归终止条件在哪? 就是叶子节点,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;
    }

另外一种思考方式,就是正着思考,我们从父节点开始往下走。传的参数里维护一个长度,还需要孩子的能练起来的TARGER的VAL,如果孩子的VAL可以满足,就更新长度。

public int longestConsecutive(TreeNode root) {
        if(root == null) return 0;
        Stack 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;
        }
    }

你可能感兴趣的:(298. Binary Tree Longest Consecutive Sequence)