首页 > 代码库 > Binary Tree Inorder Traversal
Binary Tree Inorder Traversal
思路一:递归版本
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; inorder(root, result); return result; } void inorder(TreeNode *cur, vector<int> &result) { if(cur != nullptr) { if(cur->left) inorder(cur->left, result); result.push_back(cur->val); if(cur->right) inorder(cur->right, result); } } };
思路二:非递归版本,一般二叉树的中序遍历需要记录节点出栈的次数,在中序遍历中,当节点第二次出栈时才输出对应值,这里巧妙的使用一个额外的指针实现了这个功能
以上两种方法的时间和空间复杂度都是O(n);
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; stack<TreeNode *> s; TreeNode *p = root; while(!s.empty() || p != nullptr) { if(p != nullptr) { s.push(p); p = p->left; } else { TreeNode *tmp = s.top(); result.push_back(tmp->val); s.pop(); p = tmp->right; } } return result; } };
思路三:使用Morris方法中序遍历,空间复杂度是O(1)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; TreeNode *cur = root; while(cur != nullptr) { if(cur->left == nullptr) { result.push_back(cur->val); cur = cur->right; } else { TreeNode *tmp = cur->left; while(tmp->right != nullptr && tmp->right != cur) tmp = tmp->right; if(tmp->right == nullptr) { tmp->right = cur; cur = cur->left; } else { result.push_back(cur->val); cur = cur->right; tmp->right = nullptr; } } } return result; } };
Binary Tree Inorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。