Binary Tree Inorder Traversal

来源:互联网 发布:vr与游戏美工 编辑:程序博客网 时间:2024/05/19 10:38

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?

Recursive :

/** * 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> path;        inorder(root, path);        return path;    }    void inorder(TreeNode *root, vector<int> &path){        if(root){            inorder(root->left,path);            path.push_back(root->val);            inorder(root->right,path);        }    }};


Iterative:

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

0 0
原创粉丝点击