[LeetCode]Binary Tree Inorder Traversal

来源:互联网 发布:彩票代购软件 编辑:程序博客网 时间:2024/06/05 11:32

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)

0 0
原创粉丝点击