leetcode题解-94. Binary Tree Inorder Traversal

题目: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].
其实题目就是要中序遍历二叉树的值。题目中也提到了,可以使用递归的方法,也可以使用遍历的方法。所以这里就讲两种方法的代码写出来即可。代码很简单,不做过多解释。
递归方式:

public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        // method 1: recursion

        helper(root, res);
        return res;
    }
    //helper function for method 1
    private void helper(TreeNode root, List<Integer> res) {
        if (root != null) {
            if (root.left != null) {
                helper(root.left, res);
            }
            res.add(root.val);
            if (root.right != null) {
                helper(root.right, res);
           }
       }
   }

循环方式:

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null || !stack.empty()){
            while(cur != null){
                stack.add(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }

你可能感兴趣的:(leetcode刷题)