考察非递归写法。前序遍历可以参考这篇文章,后序遍历可以参考这篇
代码:
1 vector<int> inorderTraversal(TreeNode *root) { 2 TreeNode *node = NULL; 3 stack<TreeNode *> st; 4 vector<int> path; 5 6 node = root; 7 while (node) { 8 while (node) { 9 st.push(node); 10 node = node->left; 11 } 12 node = NULL; 13 while (!st.empty() && !node) { 14 path.push_back(st.top()->val); 15 node = st.top()->right; 16 st.pop(); 17 } 18 } 19 20 return path; 21 }