tree

确定目标
问题规模(参数)必须能缩小,否则就添加参数
解决原子问题就是解决返回值的原子数据

leetcode-144-二叉树的前序遍历
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {//原问题的res
        List<Integer> res = new ArrayList<>();
        if(root==null){//问题规模(root)不能再缩小了
            return res;
        }
        List<Integer> left = preorderTraversal(root.left);//子问题的res
        List<Integer> right = preorderTraversal(root.right);//子问题的res
        //原问题的res=root.val+left+right
        res.add(root.val);
        res.addAll(left);
        res.addAll(right);
        return res;
    }
}


class Solution {
    public void preorderTraversal(TreeNode root,ArrayList<Integer> res) {//res是共享数据
        if(root==null){//问题规模(root)不能再缩小了
            return;
        }
        res.add(root.val);
        preorderTraversal(root.left,res);
        preorderTraversal(root.right,res);
    }
}
leetcode-100-same tree
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        
        if(p==null&&q==null){//问题规模(p q)不能在缩小
            return true;
        }
        //原子问题的res
        if(p!=null&&q!=null&&p.val==q.val){
            return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
        }else{
            return false;
        }
    }
}
leetcode-104-Maximum Depth of Binary Tree
class Solution {
    public int maxDepth(TreeNode root) {//原问题的res
        if(root==null)//问题规模(root)不能再缩小了
            return 0;
        //原子问题(root)
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;

    }
}
leetcode-654-Maximum Binary Tree
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return constructMaximumBinaryTree2(nums,0,nums.length-1);
    }

    private TreeNode constructMaximumBinaryTree2(int[] nums, int l, int r) {
        //问题规模(l r)不能再缩小了
        if(l>r){
            return null;
        }
        //原子问题(原问题是根据nums构建一棵树,原子问题就是根据nums构建一个node)
        int maxIdx=0,maxVal = Integer.MIN_VALUE;
        for(int i=l;i<=r;++i){
            if(nums[i]>maxVal){
                maxIdx=i;
                maxVal=nums[i];
            }
        }
        TreeNode res = new TreeNode(maxVal);
        TreeNode left = constructMaximumBinaryTree2(nums, l, maxIdx-1);
        TreeNode right = constructMaximumBinaryTree2(nums, maxIdx + 1, r);
        res.left=left;
        res.right=right;
        return res;
    }
}
原文地址:https://www.cnblogs.com/t1314/p/12337518.html