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

Leetcode: Binary Tree Inorder Traversal(二叉树中序遍历)

时间:2015-04-02 20:53:56      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:binary   tree   遍历   

题目:
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?

递归解法(C++):

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
private:
    vector<int> result;
public:
    vector<int> inorderTraversal(TreeNode *root)
    {
        if (root)
        {
            inorderTraversal(root->left);
            result.push_back(root->val);
            inorderTraversal(root->right);
        }
        return result;
    }
};

二叉树中序遍历的非递归算法和前序遍历思想差不多都是使用栈结构进行求解,参考Leetcode: Binary Tree Preorder Traversal(二叉树前序遍历)
非递归解法(C++):

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

C#非递归解法:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution
{
    public IList<int> InorderTraversal(TreeNode root)
    {
        IList<int> result = new List<int>();
        Stack<TreeNode> nodes = new Stack<TreeNode>();
        TreeNode node = root;
        //当result或者nodes不为空时
        while (node != null || nodes.Count > 0)
        {
            //node不为空的时候一直沿着左子树走,沿途节点入栈
            if (node != null)
            {
                nodes.Push(node);
                node = node.left;
            }
            //node空的时候,说明找到了最左子树
            else
            {
                //栈顶元素弹出放入result中
                node = nodes.Pop();
                result.Add(node.val);
                //node指向该节点的右子树,继续循环
                node = node.right;
            }
        }
        return result;
    }
}

Leetcode: Binary Tree Inorder Traversal(二叉树中序遍历)

标签:binary   tree   遍历   

原文地址:http://blog.csdn.net/theonegis/article/details/44837045

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