LeetCode:94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?





C++ Solution:

/**
  * 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*> stack;

        TreeNode* curr = root;

        while (curr || !stack.empty()) {
             while (curr) {
                 stack.push(curr);
                 curr = curr->left;
             }

            curr = stack.top();
             stack.pop();

            result.push_back(curr->val);

            curr = curr->right;
         }
         return result;
     }
    
     void traversal(TreeNode *root, vector<int> &list) {

        if (root != NULL) {
             if (root->left != NULL)
                 traversal(root->left, list);

            list.push_back(root->val);

            if (root->right != NULL)
                 traversal(root->right, list);
         }
     }
};

posted @ 2017-09-27 16:38  YorkYu  阅读(147)  评论(0编辑  收藏  举报