Leetcode: Binary Tree Inorder Traversal

来源:互联网 发布:复制软件手机版 编辑:程序博客网 时间:2024/06/09 14:10

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

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

跟前序遍历类似。

/** * Definition for binary tree * 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_tree;        while (root != NULL || !stack_tree.empty()) {            while (root != NULL) {                stack_tree.push(root);                root = root->left;            }            if (!stack_tree.empty()) {                root = stack_tree.top();                stack_tree.pop();                result.push_back(root->val);                root = root->right;            }        }                return result;    }};

=========================第二次============================

/** * Definition for binary tree * 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*> nodes;        while (root != NULL || !nodes.empty()) {            while (root != NULL) {                nodes.push(root);                root = root->left;            }                        if (!nodes.empty()) {                root = nodes.top();                nodes.pop();                result.push_back(root->val);                root = root->right;            }        }                return result;    }};


0 0
原创粉丝点击