Tree=0820

作者: 不学习就胖 | 来源:发表于2018-08-21 23:44 被阅读0次
    //1.doMirror
    public void doMirror(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) {
            return;
        }
        simpleSwap(root);
        doMirror(root.left);
        doMirror(root.right);
    }
    
    private void simpleSwap(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
    
    //2.findPath
    public void findPath(TreeNode root, int target, List onePath, List<List> pathList) {
        if (root == null) {
            return;
        }
        onePath.add(root.val);
        if (target == root.val && root.left == null && root.right == null) {
            pathList.add(new ArrayList<Integer>(onePath));
        }
        findPath(root.left, target - root.val, onePath, pathList);
        findPath(root.right, target - root.val, onePath, pathList);
        onePath.remove(onePath.size() - 1);
    }
    
    //3.isSub
    public Boolean isSub(TreeNode rootA, TreeNode rootB) {
        if (rootA == null || rootB == null) {
            return false;
        }
        if (rootA.val == rootB.val && isSame(rootA, rootB)) {
            return true;
        }
        return isSub(rootA.left, rootB) || isSub(rootA.right, rootB);
    }
    
    private Boolean isSame(TreeNode rootA, TreeNode rootB) {
        if (rootA == null && rootB == null) {
            return true;
        }
        if (rootA == null || rootB == null || rootA.val != rootB.val) {
            return false;
        }
        return isSame(rootA.left, rootB.left) && isSame(rootA.right, rootB.right);
    }
    
    //4.getPath
    public int getPath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(getPath(root.left), getPath(root.right)) + 1;
    }

    相关文章

      网友评论

          本文标题:Tree=0820

          本文链接:https://www.haomeiwen.com/subject/wwgsiftx.html