LintCode -- 二叉树的中序遍历

LintCode -- binary-tree-inorder-traversal(二叉树的中序遍历)

原题链接:http://www.lintcode.com/zh-cn/problem/binary-tree-inorder-traversal/


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

样例

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

   1
    \
     2
    /
   3

返回 [1,3,2].

挑战

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

非递归实现(C++、Java、Python):

/**
 * 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
        vector<TreeNode *> p;
        vector<int> res;
        while(root != NULL || p.size() != 0){
            while(root != NULL){
                p.push_back(root);
                root = root->left;
            }
            root = p.back();
            p.pop_back();
            res.push_back(root->val);
            root = root->right;
        }
        return res;
    }
};

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<TreeNode> p = new ArrayList<TreeNode>();
        ArrayList<Integer> res = new ArrayList<Integer>();
        while(root != null || p.size() != 0){
            while(root != null){
                p.add(root);
                root = root.left;
            }
            root = p.get(p.size()-1);
            p.remove(p.size()-1);
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: Inorder in ArrayList which contains node values.
    """
    def inorderTraversal(self, root):
        # write your code here
        p = [root]
        res = [0]
        while root is not None or len(p) != 1:
            while root is not None:
                p.append(root)
                root = root.left
            root = p[len(p)-1]
            del p[len(p)-1]
            res.append(root.val)
            root = root.right
        n = len(res)
        return res[1:n]



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值