标签:amp node tree node blog == ret class return log
思路一:递归版本
/** * 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; } };
标签:amp node tree node blog == ret class return log
原文地址:http://www.cnblogs.com/chengyuz/p/6657498.html