Binary Tree Inorder Traversal

递归与迭代实现二叉树中序遍历的算法对比
本文详细介绍了如何使用递归和迭代两种方法实现二叉树的中序遍历,并通过实例代码进行验证。重点讨论了两种方法的时间复杂度、空间复杂度以及各自的优缺点,旨在帮助读者理解不同场景下选择合适遍历方式的重要性。

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

Analyse: root->left, root, root->right.

1. Recursion

    Runtime: 0ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode* root) {
13         vector<int> result;
14         if(!root) return result;
15         
16         inorder(root, result);
17         return result;
18     }
19     void inorder(TreeNode* root, vector<int>& result){
20         if(root->left) inorder(root->left, result);
21         result.push_back(root->val);
22         if(root->right) inorder(root->right, result);
23     }
24 };

 

2. Iteration

    Runtime: 0ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode* root) {
13         vector<int> result;
14         if(!root) return result;
15         stack<TreeNode* > stk;
16         
17         while(root || !stk.empty()){
18             if(root){
19                 stk.push(root);
20                 root = root->left;
21             }
22             else{
23                 root = stk.top();
24                 result.push_back(root->val);
25                 stk.pop();
26                 root = root->right;
27             }
28         }
29         return result;
30     }
31 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4679898.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值