阅读654 返回首页    go 阿里云 go 技术社区[云栖]


LeetCode题目详解——Binary Tree Inorder Traversal

题目:

Given a binary tree, return the preorder 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?

中序遍历和先序遍历有很多相似的地方,只是在访问的顺序上有一点不太一样。非递归的遍历同样分为使用栈和不使用栈的方式。

一、使用栈

class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        stack<TreeNode*> rest;
        vector<int> result;
        rest.push(root);
        TreeNode *cur;

        if(root == NULL)
            return result;
        cur=root;
        while(!rest.empty() || cur)
        {
            while (cur) {
                rest.push(cur);
                cur = cur->left;
            }
            if(!rest.empty())
            {
                cur = rest.top();
                result.push_back(cur->val);
                rest.pop();
                cur=cur->right;
            }
        }
        return result;
    }
};


、不使用栈

不使用栈的方法即morris方法,利用改变树的结构,来记录接下来需要访问的节点。morris方法的先序遍历和中序遍历很相似,只有一句代码的位置不一样。对于morris方法不太了解的同学可以参考的前一篇文章:LeetCode题目详解——Binary Tree Preorder Traversal 代码如下:
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> result;
        TreeNode *p=root;
        if(!root)
            return result;
        while(p)
        {
            if(p->left==NULL)
            {
                result.push_back(p->val);
                p=p->right;
            }
            else
            {
                TreeNode *tmp=p->left;
                while(tmp->right && tmp->right!=p)
                {
                    tmp=tmp->right;
                }
                if(tmp->right==NULL)
                {
                    tmp->right=p;
                    p=p->left;
                }
                else
                {
                    result.push_back(p->val);//只有这句代码的位置和先序遍历的时候不太一样
                    tmp->right=NULL;
                    p=p->right;
                }
            }
        }
        return result;
    }
    
};


最后更新:2017-04-03 05:39:57

  上一篇:go Kafka详解五、Kafka Consumer的底层API- SimpleConsumer
  下一篇:go Asp.net相关书籍