Leetcode--102. 二叉树的层次遍历
給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。
例如:
給定二叉樹:?[3,9,20,null,null,15,7],
? ? 3
? ?/ \
? 9 ?20
? ? / ?\
? ?15 ? 7
返回其層次遍歷結果:
[
? [3],
? [9,20],
? [15,7]
]
提交的代碼:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????List<List<Integer>>?levels?=?new?ArrayList<List<Integer>>();
????public?void?fun(TreeNode?root,int?hight)
????{
????????if(levels.size()?==?hight)
????????{
????????????levels.add(new?ArrayList<Integer>());
????????}
?????????levels.get(hight).add(root.val);
?????????if(root.left!=null)
?????????{
?????????????fun(root.left,hight+1);
?????????}
?????????if(root.right!=null)
?????????{
?????????????fun(root.right,hight+1);
?????????}
????}
????public?List<List<Integer>>?levelOrder(TreeNode?root)?{
?????????if?(root?==?null)?return?levels;
????????fun(root,0);
????????return?levels;
????}
}
總結
以上是生活随笔為你收集整理的Leetcode--102. 二叉树的层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【剑指offer】面试题03:数组中重复
- 下一篇: Leetcode--142. 环形链表Ⅱ