返回介绍

solution / 0100-0199 / 0107.Binary Tree Level Order Traversal II / README_EN

发布于 2024-06-17 01:04:05 字数 8488 浏览 0 评论 0 收藏 0

107. Binary Tree Level Order Traversal II

中文文档

Description

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

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Solutions

Solution 1: BFS

We can use the BFS (Breadth-First Search) method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty:

  • Traverse all nodes in the current queue, store their values in a temporary array $t$, and then enqueue their child nodes.
  • Store the temporary array $t$ in the answer array.

Finally, return the reversed answer array.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
    ans = []
    if root is None:
      return ans
    q = deque([root])
    while q:
      t = []
      for _ in range(len(q)):
        node = q.popleft()
        t.append(node.val)
        if node.left:
          q.append(node.left)
        if node.right:
          q.append(node.right)
      ans.append(t)
    return ans[::-1]
/**
 * 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 {
  public List<List<Integer>> levelOrderBottom(TreeNode root) {
    LinkedList<List<Integer>> ans = new LinkedList<>();
    if (root == null) {
      return ans;
    }
    Deque<TreeNode> q = new LinkedList<>();
    q.offerLast(root);
    while (!q.isEmpty()) {
      List<Integer> t = new ArrayList<>();
      for (int i = q.size(); i > 0; --i) {
        TreeNode node = q.pollFirst();
        t.add(node.val);
        if (node.left != null) {
          q.offerLast(node.left);
        }
        if (node.right != null) {
          q.offerLast(node.right);
        }
      }
      ans.addFirst(t);
    }
    return ans;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  vector<vector<int>> levelOrderBottom(TreeNode* root) {
    vector<vector<int>> ans;
    if (!root) {
      return ans;
    }
    queue<TreeNode*> q{{root}};
    while (!q.empty()) {
      vector<int> t;
      for (int n = q.size(); n; --n) {
        auto node = q.front();
        q.pop();
        t.push_back(node->val);
        if (node->left) {
          q.push(node->left);
        }
        if (node->right) {
          q.push(node->right);
        }
      }
      ans.push_back(t);
    }
    reverse(ans.begin(), ans.end());
    return ans;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func levelOrderBottom(root *TreeNode) (ans [][]int) {
  if root == nil {
    return
  }
  q := []*TreeNode{root}
  for len(q) > 0 {
    t := []int{}
    for n := len(q); n > 0; n-- {
      node := q[0]
      q = q[1:]
      t = append(t, node.Val)
      if node.Left != nil {
        q = append(q, node.Left)
      }
      if node.Right != nil {
        q = append(q, node.Right)
      }
    }
    ans = append(ans, t)
  }
  for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
    ans[i], ans[j] = ans[j], ans[i]
  }
  return
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function levelOrderBottom(root: TreeNode | null): number[][] {
  const ans: number[][] = [];
  if (!root) {
    return ans;
  }
  const q: TreeNode[] = [root];
  while (q.length) {
    const t: number[] = [];
    const qq: TreeNode[] = [];
    for (const { val, left, right } of q) {
      t.push(val);
      left && qq.push(left);
      right && qq.push(right);
    }
    ans.push(t);
    q.splice(0, q.length, ...qq);
  }
  return ans.reverse();
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::{ rc::Rc, cell::RefCell, collections::VecDeque };
impl Solution {
  pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
    let mut ans = Vec::new();
    if let Some(root_node) = root {
      let mut q = VecDeque::new();
      q.push_back(root_node);
      while !q.is_empty() {
        let mut t = Vec::new();
        for _ in 0..q.len() {
          if let Some(node) = q.pop_front() {
            let node_ref = node.borrow();
            t.push(node_ref.val);
            if let Some(ref left) = node_ref.left {
              q.push_back(Rc::clone(left));
            }
            if let Some(ref right) = node_ref.right {
              q.push_back(Rc::clone(right));
            }
          }
        }
        ans.push(t);
      }
    }
    ans.reverse();
    ans
  }
}
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.left = (left===undefined ? null : left)
 *   this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = function (root) {
  const ans = [];
  if (!root) {
    return ans;
  }
  const q = [root];
  while (q.length) {
    const t = [];
    const qq = [];
    for (const { val, left, right } of q) {
      t.push(val);
      left && qq.push(left);
      right && qq.push(right);
    }
    ans.push(t);
    q.splice(0, q.length, ...qq);
  }
  return ans.reverse();
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文