Binary Tree Inorder Traversal

来源:互联网 发布:淘宝直通车溢价比例 编辑:程序博客网 时间:2024/06/16 17:13

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?

Subscribe to see which companies asked this question

/** * 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;        const TreeNode *p = root;        stack<const TreeNode *> s;        while (!s.empty() || p != nullptr) {            if (p != nullptr) {                s.push(p);               p = p->left;            } else {             p = s.top();                s.pop();                result.push_back(p->val);               p = p->right;            }        }        return result;    }};


0 0
原创粉丝点击