本篇文章为大家展示了如何解析python二叉树的右视图,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
答案:
1public List<Integer> rightSideView(TreeNode root) { 2 if (root == null) 3 return new ArrayList(); 4 Queue<TreeNode> queue = new LinkedList(); 5 queue.offer(root); 6 List<Integer> res = new ArrayList(); 7 while (!queue.isEmpty()) { 8 int size = queue.size(); 9 while (size-- > 0) {10 TreeNode cur = queue.poll();11 if (size == 0)12 res.add(cur.val);13 if (cur.left != null)14 queue.offer(cur.left);15 if (cur.right != null)16 queue.offer(cur.right);17 }18 }19 return res;20}
解析:
原理很简单,我们通过bfs(广度优先搜索)遍历每一行,然后记录一下每一行的最右的那个节点即可。在看一种递归的解法
1public List<Integer> rightSideView(TreeNode root) { 2 List<Integer> result = new ArrayList<Integer>(); 3 rightView(root, result, 0); 4 return result; 5} 6 7public void rightView(TreeNode curr, List<Integer> result, int currDepth) { 8 if (curr == null) { 9 return;10 }11 if (currDepth == result.size()) {12 result.add(curr.val);13 }14 rightView(curr.right, result, currDepth + 1);15 rightView(curr.left, result, currDepth + 1);16}
通过dfs(深度优先搜索)遍历每一个节点,他先遍历的是右节点,然后是左节点,当遍历的深度等于result的长度的时候,把当前节点加入到result中。
上述内容就是如何解析python二叉树的右视图,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/1010616/blog/4440331