1. 程式人生 > 實用技巧 >leetcode94 - Binary Tree Inorder Traversal - medium

leetcode94 - Binary Tree Inorder Traversal - medium

Given a binary tree, return theinordertraversal 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?

Inorder: root in the middle 先一路traverse到最左邊的leaf node,一路上把經過的node都push進stack。最先pop出來的就是起點,也相當於一個夾在中間的root(它的left child是null),所以去到它的right child,再如此迴圈。因為不涉及修改node,直接拿root來traverse就行,stack裡都是相對來說的left node。 實現:
class
Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; while (!st.empty() || root){ while (root){ st.push(root); root
= root->left; } root = st.top(); st.pop(); res.push_back(root->val); root = root->right; } return res; } };