Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-08-22 #337

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-08-22

SaraadKun commented 2 years ago

655. 输出二叉树

class Solution {

    int m, n;
    List<List<String>> ans;
    public List<List<String>> printTree(TreeNode root) {
        m = high(root);
        n = (1 << m) - 1;
        ans = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            List<String> row = new ArrayList<>();
            for (int j = 0; j < n; j++) {
                row.add("");
            }
            ans.add(row);
        }
        dfs(root, 0, n / 2);
        return ans;
    }

    private void dfs(TreeNode root, int row, int col) {
        if (root == null) {
            return;
        }
        ans.get(row).set(col, String.valueOf(root.val));
        dfs(root.left, row + 1, col - (1 << ans.size() - row - 2));
        dfs(root.right, row + 1, col + (1 << ans.size() - row - 2));
    }

    private int high(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(high(root.left), high(root.right)) + 1;
    }
}

WeChat: Saraad

gongpeione commented 2 years ago
/*
 * @lc app=leetcode id=104 lang=typescript
 *
 * [104] Maximum Depth of Binary Tree
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxDepth(root: TreeNode | null): number {
    let max = 0;

    const dfs = (node, depth = 0) => {
        if (!node) return;

        depth++;

        dfs(node.left, depth);
        dfs(node.right, depth);

        max = Math.max(max, depth);
    }

    dfs(root);

    return max;
};
// @lc code=end

微信id: 弘树 来自 vscode 插件