首页 > 编程语言 > 详细

力扣算法题—094中序遍历二叉树【】

时间:2019-04-29 00:11:42      阅读:191      评论:0      收藏:0      [点我收藏+]

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
         2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

 

 

 1 //递归遍历
 2 class Solution {
 3 public:
 4     vector<int> inorderTraversal(TreeNode* root) {
 5         vector<int>res;
 6         helper(res, root);
 7         return res;
 8     }
 9     void helper(vector<int>&res, TreeNode* root) {
10         if (root==NULL)
11             return;
12         if (root->left)
13             helper(res, root->left);
14         res.push_back(root->val);
15         if (root->right)
16             helper(res, root->right);
17     }
18 };
19 
20 
21 //非递归遍历
22 class Solution {
23 public:
24     vector<int> inorderTraversal(TreeNode* root) {
25         vector<int>res;
26         stack<TreeNode*>s;
27         TreeNode* p = root;
28         while (p || !s.empty()) {
29             while (p) {
30                 s.push(p);
31                 p = p->left;
32             }//找到最左节点
33             p = s.top();
34             s.pop();
35             res.push_back(p->val);
36             p = p->right;
37         }
38         return res;
39     }
40 };
41 
42 
43 //另一种解法
44 // Non-recursion and no stack
45 class Solution {
46 public:
47     vector<int> inorderTraversal(TreeNode *root) {
48         vector<int> res;
49         if (!root) return res;
50         TreeNode *cur, *pre;
51         cur = root;
52         while (cur) {
53             if (!cur->left) {
54                 res.push_back(cur->val);
55                 cur = cur->right;
56             }
57             else {
58                 pre = cur->left;
59                 while (pre->right && pre->right != cur) pre = pre->right;
60                 if (!pre->right) {
61                     pre->right = cur;
62                     cur = cur->left;
63                 }
64                 else {
65                     pre->right = NULL;
66                     res.push_back(cur->val);
67                     cur = cur->right;
68                 }
69             }
70         }
71         return res;
72     }
73 };

 

力扣算法题—094中序遍历二叉树【】

原文:https://www.cnblogs.com/zzw1024/p/10787632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!