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

leetcode No94. Binary Tree Inorder Traversal

时间:2016-08-14 02:05:16      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

Question:

Given a binary tree, return the inorder traversal of its nodes‘ values.

For example:
Given binary tree [1,null,2,3],

   1
         2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

中序遍历,左-根-右

Algorithm:

递归,和非递归两种方法,见程序

Accepted Code:

法一:递归     相当慢
/**
 * 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> res;
    vector<int> inorderTraversal(TreeNode* root) {
        if(root!=NULL)
        {
           inorderTraversal(root->left);
           res.push_back(root->val);
           inorderTraversal(root->right);
        }
        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*> stack;
        TreeNode* pNode=root;
        while(pNode||!stack.empty())
        {
            if(pNode!=NULL)   //节点不为空,加入栈中,并访问节点左子树
            {
                stack.push(pNode);
                pNode=pNode->left;
            }
            else
            {
                pNode=stack.top();     //节点为空,从栈中弹出一个节点,访问这个节点
                stack.pop();
                res.push_back(pNode->val);    
                pNode=pNode->right;    //访问节点右子树
            }
        }
        return res;
    }
};


leetcode No94. Binary Tree Inorder Traversal

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52201639

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