94. Binary Tree Inorder Traversal

问题

二叉树的中序遍历。

思路

递归,注意递归的顺序就好了。左节点->父节点->右节点。二叉树的三序遍历,包含前序、中序、后序遍历,这里的顺序指的对象都是父节点。

答案

1. 递归版

c++版,耗时0ms:

/**
 * 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;
        if(!root)
            return res;
        solve(root,res);
        return res;
    }
    void solve(TreeNode* root, vector<int>&res){
        if(!root)
            return;
        solve(root->left, res);
        res.push_back(root->val);
        solve(root->right, res);
    }
};

java版,用时1ms:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        //special case
        if(root==null) return res;
        //the terminal condition of the recursion, must have the return value
        if(root.left==null&&root.right==null) {
            res.add(root.val);
            return res;
        }

        if(root.left!=null) res.addAll(inorderTraversal(root.left));

        res.add(root.val);

        if(root.right!=null) res.addAll(inorderTraversal(root.right));

        return res;
    }
}

2. 非递归版

非递归版只能用栈来保存现场,然后利用前进-回溯的思想完成。

java版,耗时2ms:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        if(root==null) return res;
        Stack<TreeNode> stack = new Stack();
        TreeNode node = root;
        while(node!=null){
            stack.push(node);
            node=node.left;
        }
        while(stack.size()>0){
            TreeNode top = stack.pop();
            res.add(top.val);
            if(top.right!=null){
                node = top.right;
                while(node!=null){
                    stack.push(node);
                    node = node.left;
                }
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值