leetcode655-输出二叉树

输出二叉树

  • DFS
class Solution {
    List<List<String>> res = new ArrayList<>();
    int m, n, height;
    public List<List<String>> printTree(TreeNode root) {
        height = callDepth(root);
        m = height+1;
        n = (1 << (height+1))-1;
        for(int i = 0; i < m; i++){
            List<String> tmp = new ArrayList<>();
            for(int j = 0; j < n; j++)  tmp.add("");
            res.add(tmp);
        }
        dfs(root, 0, (n-1)/2);
        return res;
    }
    public void dfs(TreeNode root, int r, int c){
        if(root == null)    return;
        res.get(r).set(c, String.valueOf(root.val));
        dfs(root.left, r+1, c-(1 << (height-r-1)));
        dfs(root.right, r+1, c+(1 << (height-r-1)));
    }
    public int callDepth(TreeNode root){
        int h = 0;
        if(root.left != null)   h = Math.max(h, callDepth(root.left)+1);
        if(root.right != null)  h = Math.max(h, callDepth(root.right)+1);
        return h;
    }
}

  • BFS
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    class Tuple{
        TreeNode node;
        int r, c;
        public Tuple(TreeNode node, int r, int c){
            this.node = node;
            this.r = r;
            this.c = c;
        }
    }
    public List<List<String>> printTree(TreeNode root) {
        List<List<String>> res = new ArrayList<>();
        int height = callDepth(root);
        int m = height+1, n = (1 << (height+1))-1;
        for(int i = 0; i < m; i++){
            List<String> tmp = new ArrayList<>();
            for(int j = 0; j < n; j++)  tmp.add("");
            res.add(tmp);
        }
        Queue<Tuple> q = new ArrayDeque<>();
        q.offer(new Tuple(root, 0, (n-1)/2));
        while(!q.isEmpty()){
            Tuple t = q.poll();
            TreeNode node = t.node;
            int r = t.r, c = t.c;
            res.get(r).set(c, String.valueOf(node.val));
            if(node.left != null)   q.offer(new Tuple(node.left, r+1, c-(1 << (height-r-1))));
            if(node.right != null)  q.offer(new Tuple(node.right, r+1, c+(1 << (height-r-1))));
        }
        return res;
    }
    public int callDepth(TreeNode root){
        int h = 0;
        if(root.left != null)   h = Math.max(h, callDepth(root.left)+1);
        if(root.right != null)  h = Math.max(h, callDepth(root.right)+1);
        return h;
    }
}
posted @ 2022-08-22 15:31  xzh-yyds  阅读(27)  评论(0)    收藏  举报