LeetCode(94)——Binary Tree Inorder Traversal

題目:

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

 

中序遍歷

AC:

public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> resultList = new LinkedList<>();
        if (root == null) {
            return resultList;
        }
        
        helper(resultList, root);
        
        return resultList;
    }
    
    private void helper(List<Integer> resultList, TreeNode root) {
        if (root.left != null) {
            helper(resultList, root.left);
        }
        
        resultList.add(root.val);
        
        if (root.right != null) {
            helper(resultList, root.right);
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章