问题描述
Given a binary tree, return the inorder traversal of its nodes' values. (左 - 根 - 右)
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
知识兔Follow up: Recursive solution is trivial, could you do it iteratively?
参考答案
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 // init
14 vector<int> res;
15 stack<TreeNode* > st;
16 TreeNode* p = root; // 初始化根节点
17
18 while(p||!st.empty()){
19 // 一旦遇到节点,先考虑左边的,直到尽头,如果没有之后的右node,就停止运行了
20 while(p){
21 st.push(p);
22 p = p->left;
23 }
24 // 立刻提取p的信息,并且把p弹出来。如果进入while,那么这一步只会是左孩子,如果没进入while,那么会是父节点/右节点。
25 p = st.top();
26 st.pop();
27 res.push_back(p->val);
28 // 把p 变成p的右孩子
29 p = p->right;
30 }
31 return res;
32 }
33 };
知识兔