码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode || 94、Binary Tree Inorder Traversal

时间:2015-04-16 10:27:18      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:二叉树   leetcode   中序遍历   stack   递归   

problem:

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.

Hide Tags
 Tree Hash Table Stack
题意:二叉树的中序遍历

thinking:

(1)二叉树的中序遍历,给出递归法和非递归法两种。

(2)递归法的思路是,先递归访问当前结点的左孩子,再打印当前结点的值,再递归访问当前结点的右孩子。

(3)非递归法是借助堆栈实现的,思路也是先将所有左孩子节点放入堆栈中,左孩子为NULL时,打印堆栈顶点结点,
          出栈,访问其右孩子。如果其右孩子的左孩子不为NULL,重复上述过程。

code:

非递归法:

class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
           vector<int> ret;
           stack<TreeNode*> _stack;
           TreeNode *tmp=root;
           while(tmp!=NULL || !_stack.empty())
           {
               if(tmp!=NULL)
               {
                   _stack.push(tmp);
                   tmp=tmp->left;
               }
               else
               {
                   tmp=_stack.top();
                   _stack.pop();
                   ret.push_back(tmp->val);
                   tmp=tmp->right;
               }
           }
         return ret;   
    }
};

递归法:

class Solution {
private:
    vector<int> ret;
public:
    vector<int> inorderTraversal(TreeNode *root) {
       
            inorder(root);
            return ret;        
        
    }
protected:
    void inorder(TreeNode *node)
    {
        if(node!=NULL)
        {
            inorder(node->left);
            ret.push_back(node->val);
            inorder(node->right);
        }
    }
};


leetcode || 94、Binary Tree Inorder Traversal

标签:二叉树   leetcode   中序遍历   stack   递归   

原文地址:http://blog.csdn.net/hustyangju/article/details/45070335

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!