Lintcode 二叉树的中序遍历

来源:互联网 发布:ping远程ip的8080端口 编辑:程序博客网 时间:2024/05/21 10:44

给出一棵二叉树,返回其中序遍历

样例

给出二叉树 {1,#,2,3},

   1    \     2    /   3

返回 [1,3,2].

挑战 

你能使用非递归算法来实现么?

标签 
递归 二叉树 二叉树遍历
方法一    递归

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in vector which contains node values.     */public:     void inorder(TreeNode *root,vector<int> &result) {         if(root->left!=NULL)         inorder(root->left,result);                  result.push_back(root->val);                  if(root->right!=NULL)         inorder(root->right,result);     }        vector<int> inorderTraversal(TreeNode *root) {        // write your code here        vector<int> result;        if(root==NULL)        return result;        inorder(root,result);        return result;    }};


方法二    非递归


/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in vector which contains node values.     */public:    vector<int> inorderTraversal(TreeNode *root) {        // write your code here        stack<TreeNode*> s;        vector<int> result;        if(root==NULL)        return result;                while(root!=NULL||!s.empty()){            while(root!=NULL){                s.push(root);                root=root->left;            }                       root=s.top();            s.pop();            result.push_back(root->val);            root=root->right;            }        return result;        }    };


如有问题请留言。

如有帮助请顶一个,你们的支持是我最大的动力。

文章均可以转载,但请注明文章链接,谢谢。

0 0
原创粉丝点击