二叉树中序遍历复习

来源:互联网 发布:数据帧的结构 编辑:程序博客网 时间:2024/06/18 11:34

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?

解答如下(注释为递归方法,复杂度太大,通不过测试):

/** * 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) {        stack<TreeNode*> Stack;        vector<int> value;        TreeNode *ptr;        ptr = root;        while (ptr != NULL || !Stack.empty())        {            if (ptr != NULL)            {               Stack.push(ptr);               ptr = ptr->left;            }            else            {                ptr = Stack.top();                Stack.pop();                value.push_back(ptr->val);                ptr = ptr->right;            }        }         return value;    }        /*        vector<int> value;        if (root == NULL)          return value;        if (root->left == NULL && root->right == NULL)        {            value.push_back(root->val);            return value;        }        while (root->left != NULL || root->right != NULL){        if (root->left != NULL)          inorderTraversal(root->left);        value.push_back(root->val);        if (root->right != NULL)          inorderTraversal(root->right);        }        return value;    }    */};
1 0