博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 366: Find Leaves of Binary Tree
阅读量:5080 次
发布时间:2019-06-12

本文共 2243 字,大约阅读时间需要 7 分钟。

Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:

Given binary tree 

1         / \        2   3       / \           4   5

 

Returns [4, 5, 3], [2], [1].

Explanation:

1. Removing the leaves [4, 5, 3] would result in this tree:

1         /         2

 

2. Now removing the leaf [2] would result in this tree:

1

 

3. Now removing the leaf [1] would result in the empty tree:

[]

 

 

Returns [4, 5, 3], [2], [1].

 

 

 

1 /** 2  * Definition for a binary tree node. 3  * public class TreeNode { 4  *     public int val; 5  *     public TreeNode left; 6  *     public TreeNode right; 7  *     public TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public IList
> FindLeaves(TreeNode root) {12 var result = new List
>();13 if (result == null) return result;14 15 Height(root, result);16 return result;17 }18 19 private int Height(TreeNode node, IList
> result)20 {21 if (node == null) return -1;22 int h = 1 + Math.Max(Height(node.left, result), Height(node.right, result));23 24 if (h >= result.Count)25 {26 result.Add(new List
());27 }28 29 result[h].Add(node.val);30 31 return h;32 }33 }34 35 public class Solution1 {36 public IList
> FindLeaves(TreeNode root) {37 var result = new List
>();38 if (result == null) return result;39 40 var leaves = new HashSet
();41 leaves.Add(null);42 43 while (!leaves.Contains(root))44 {45 var list = new List
();46 DFS(root, leaves, list);47 result.Add(list);48 }49 50 return result;51 }52 53 private void DFS(TreeNode node, HashSet
leaves, IList
result)54 {55 if (leaves.Contains(node)) return;56 if (leaves.Contains(node.left) && leaves.Contains(node.right))57 {58 result.Add(node.val);59 leaves.Add(node);60 return;61 }62 63 DFS(node.left, leaves, result);64 DFS(node.right, leaves, result);65 }66 }

 

转载于:https://www.cnblogs.com/liangmou/p/8166003.html

你可能感兴趣的文章
CSS之不常用但重要的样式总结
查看>>
Python编译错误总结
查看>>
URL编码与解码
查看>>
日常开发时遇到的一些坑(三)
查看>>
Eclipse 安装SVN插件
查看>>
深度学习
查看>>
TCP粘包问题及解决方案
查看>>
构建之法阅读笔记02
查看>>
添加按钮
查看>>
移动端页面开发适配 rem布局原理
查看>>
Ajax中文乱码问题解决方法(服务器端用servlet)
查看>>
会计电算化常考题目一
查看>>
阿里云服务器CentOS6.9安装Mysql
查看>>
剑指offer系列6:数值的整数次方
查看>>
js 过滤敏感词
查看>>
poj2752 Seek the Name, Seek the Fame
查看>>
软件开发和软件测试,我该如何选择?(蜗牛学院)
查看>>
基本封装方法
查看>>
bcb ole拖拽功能的实现
查看>>
生活大爆炸之何为光速
查看>>