LeetCode *** 94. Binary Tree Inorder Traversal

来源:互联网 发布:个人网站域名名字 编辑:程序博客网 时间:2024/05/21 07:55

题目:

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 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> res;        if(root==NULL)return res;                stack<TreeNode*> tree;        stack<bool> visited;                tree.push(root);        visited.push(false);                while(!tree.empty()){            TreeNode *tmp=tree.top();            bool isV=visited.top();            visited.pop();                        if(tmp->left&&!isV){                tree.push(tmp->left);                isV=true;                visited.push(isV);                visited.push(false);                continue;            }                        tree.pop();                        res.push_back(tmp->val);                        if(tmp->right){                tree.push(tmp->right);                visited.push(false);            }        }                return res;    }};



愚蠢的代码,更新一个好一点的代码:

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


0 0
原创粉丝点击