94. Binary Tree Inorder Traversal

来源:互联网 发布:淘宝的彪马官方旗舰店 编辑:程序博客网 时间:2024/06/06 00:19

Title

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

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

这里写图片描述

return [1,3,2].

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

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> v;        stack<TreeNode *> s;        TreeNode *p = root;        while(p || !s.empty()) {            //left node is not null, continue            while(p) {                s.push(p);                p = p->left;               }            //output this node, and then right node            if(!s.empty()) {                p = s.top();                int x = p->val;                s.pop();                v.push_back(x);                p = p->right;            }        }        return v;    }};

runtime: 0ms

直接测试,通过。

0 0