当前位置:   article > 正文

LeetCode@107_Binary_Tree_Level_Order_Traversal_II

107_binary_tree_level_order_traversal_ii

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

java:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. Queue<TreeNode> queue = new LinkedList<>();
  12. List<Integer> treeVal = new LinkedList<>();
  13. List<List<Integer>> res = new LinkedList<>();
  14. public List<List<Integer>> levelOrderBottom(TreeNode root)
  15. {
  16. if (root == null)
  17. return res;
  18. queue.add(root);
  19. treeVal.add(root.val);
  20. res.add(treeVal);
  21. while (!queue.isEmpty())
  22. {
  23. List<Integer> currVal = new LinkedList<>();
  24. //需要判断有多少个subtreeval e.t level2 有两个数值【2,3】
  25. //#############
  26. int len = queue.size();
  27. for(int i =0;i<len;i++)
  28. {
  29. TreeNode currNode = queue.poll();
  30. if (currNode.left != null)
  31. {
  32. currVal.add(currNode.left.val);
  33. queue.add(currNode.left);
  34. }
  35. if (currNode.right != null)
  36. {
  37. currVal.add(currNode.right.val);
  38. queue.add(currNode.right);
  39. }
  40. }
  41. if (!currVal.isEmpty())
  42. {
  43. res.add(currVal);
  44. }
  45. }
  46. Collections.reverse(res);
  47. return res;
  48. }
  49. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/程序质量控制师/article/detail/62915
推荐阅读
相关标签
  

闽ICP备14008679号