[LeetCode]Binary Tree Inorder Traversal

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?


本题难度Medium。有2种算法分别是:递归法和迭代法

【思路】
本题是要对二叉树进行中序遍历。递归法很简单,但迭代法稍微难点。其实迭代法就是把递归法中的第15行与16-17行进行了分离。

1、递归法

【复杂度】
时间 O(N) 空间 O(1)

【代码】

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        //require
        List<Integer> ans=new LinkedList<>();
        //invariant
        helper(root,ans);
        //ensure
        return ans;
    }
    private void helper(TreeNode root,List<Integer> ans){
        //base case
        if(root==null)
            return;

        helper(root.left,ans);
        ans.add(root.val);
        helper(root.right,ans);
    }
}

2、迭代法

【复杂度】
时间 O(N) 空间 O(1)

【注意】
循环条件为:while(root!=null||!stack.isEmpty())

【代码】

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        //require
        List<Integer> ans=new LinkedList<>();
        Stack<TreeNode> stack=new Stack<>();
        //invariant
        while(root!=null||!stack.isEmpty()){
            if(root!=null){
                stack.push(root);//这两行对应递归法的
                root=root.left;  // helper(root.left,ans);
            }else{
                root=stack.pop(); //这三行对应递归法的
                ans.add(root.val);//ans.add(root.val);
                root=root.right;  //helper(root.right,ans);
            }
        }
        //ensure
        return ans;
    }
}

参考

Leetcode – Binary Tree Inorder Traversal (Java)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值