[LeetCode] Binary Tree Preorder Traversal

本文详细介绍了三种二叉树前序遍历方法:迭代使用栈、递归和Morris遍历。每种方法的时间复杂度均为O(n),但空间复杂度有所不同,分别为O(n)、O(n)和O(1)。通过实例代码对比分析了各自的特点和适用场景。

This is a fundamental and yet classic problem. I share my three solutions here:

  1. Iterative solution using stack --- O(n) time and O(n) space;
  2. Recursive solution --- O(n) time and O(n) space (considering the spaces of call stack);
  3. Morris traversal --- O(n) time and O(1) space!!!

Iterative solution using stack:

 1     vector<int> preorderTraversal(TreeNode* root) {
 2          vector<int> nodes;
 3          stack<TreeNode*> toVisit;
 4          TreeNode* curNode = root;
 5          while (curNode || !toVisit.empty()) {
 6              if (curNode) {
 7                  nodes.push_back(curNode -> val);
 8                  if (curNode -> right) toVisit.push(curNode -> right);
 9                  curNode = curNode -> left;
10              }
11              else {
12                  curNode = toVisit.top();
13                  toVisit.pop();
14              }
15          }
16          return nodes;
17     }

Recursive soltuion:

 1 void preorder(TreeNode* root, vector<int>& nodes) {
 2     if (!root) return;
 3     nodes.push_back(root -> val);
 4     preorder(root -> left, nodes);
 5     preorder(root -> right, nodes);
 6 } 
 7 vector<int> preorderTraversal(TreeNode* root) {
 8     vector<int> nodes;
 9     preorder(root, nodes);
10     return nodes;
11 } 

Morris traversal:

 1 vector<int> preorderTraversal(TreeNode* root) {
 2     TreeNode* curNode = root;
 3     vector<int> nodes;
 4     while (curNode) {
 5         if (curNode -> left) {
 6             TreeNode* predecessor = curNode -> left;
 7             while (predecessor -> right && predecessor -> right != curNode)
 8                 predecessor = predecessor -> right;
 9             if (!(predecessor -> right)) {
10                 nodes.push_back(curNode -> val);
11                 predecessor -> right = curNode;
12                 curNode = curNode -> left;
13             }
14             else {
15                 predecessor -> right = NULL;
16                 curNode = curNode -> right;
17             }
18         }
19         else {
20             nodes.push_back(curNode -> val);
21             curNode = curNode -> right;
22         }
23     }
24     return nodes;
25 }

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4548010.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值