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;
}
}
本文作者:xzh-yyds
本文链接:https://www.cnblogs.com/xzh-yyds/p/16612968.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探