LeetCode. 314 Binary Tree Vertical Order Traversal

本文介绍了一种二叉树的垂直遍历算法,通过跟踪每个节点的列号实现从左到右的打印顺序。文章提供了两种方法:使用哈希映射的方法便于理解和实现;另一种方法则专注于遍历顺序本身,不进行数据存储,从而降低了空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The basic idea to attach each node a col number. When goes to node->left. col -1, goes to right, col + 1. It will make things easier using a hashmap to store the nodes and correpsonding col number.


1: first method, using hashmap. It is easy to resolve.

2. Sometimes, we just want the order but not to store the data.

/*
  Vertical order traversal of binary tree.
  Since, we just need to print the order out, hashmap way is not necessary.
*/

// Since we dont need to store the data. it is good for traversal then.
/*
  Struct TreeNode {
    int val;
    TreeNode* right;
    TreeNode* left;
  };
*/

void findRange(TreeNode* root, int& leftRange, int& rightRange, int dep) {
  if(!root) return;
  if(dep < leftRange) leftRange  = dep;
  if(dep > rightRange) rightRange = dep;
  findRange(root->left, leftRange, rightRange, dep - 1);
  findRange(root->right, leftRange, rightRange, dep + 1);
}

void verticalOrder(TreeNode* root, int dep, int range) {
  if(!root) return;
  if(dep == range) cout << root->val << " ";
  verticalOrder(root->left, dep - 1, range);
  verticalOrder(root->right, dep + 1, range);
}
// Time Complexity is O(MN), M is the width of Binary Tree. N is the number of nodes in binary tree.
// Space complexity??? how to calculate.... ????
 void verticalOrder(TreeNode* root) {
  int minRange = 0, maxRange = 0;
  findRange(root, minRange, maxRange, 0);
  for(int line_no = minRange; line_no <= maxRange; ++line_no) {
    verticalOrder(root, dep, line_no);
    cout << endl;
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值