[leetcode] Binary Tree Inorder Traversal

来源:互联网 发布:法国 知乎 编辑:程序博客网 时间:2024/05/20 18:48

From : https://leetcode.com/problems/binary-tree-inorder-traversal/

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/** * 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) return res;        stack<TreeNode> box;        box.push(*root);        TreeNode *cur;        while(!box.empty()) {            cur = &(box.top());            while(cur->left) {                cur = cur->left;                box.push(*cur);            }            box.pop();            res.push_back(cur->val);            if(cur->right) {box.push(*cur->right);            } else {                while(!box.empty()) {                    cur = &(box.top());                    box.pop();                    res.push_back(cur->val);                    if(cur->right) {                        box.push(*cur->right);                        break;                    }                }            }        }        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;        if(!root) return res;        stack<TreeNode> box;        TreeNode* cur = root;        while(!box.empty() || cur){            if(cur){                box.push(*cur);                cur = cur->left;            } else {                TreeNode t = box.top();                box.pop();                res.push_back(t.val);                cur = t.right;            }        }        return res;    }};

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<Integer>();if (root == null) {return ans;}Stack<TreeNode> box = new Stack<TreeNode>();TreeNode cur = root;while (!box.isEmpty() || cur != null) {if (cur != null) {box.push(cur);cur = cur.left;} else {TreeNode t = box.pop();ans.add(t.val);cur = t.right;}}return ans;    }}


0 0
原创粉丝点击