当前位置: 代码迷 >> 综合 >> leetcode-94 Binary Tree Inorder Traversal
  详细解决方案

leetcode-94 Binary Tree Inorder Traversal

热度:27   发布时间:2023-12-16 05:34:04.0

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

Example:

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

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

 

题意就是中序得出结果集,直接调用递归实现方法如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        addRes(res,root);
        return res;
    }
    
    public void addRes(List<Integer> res,TreeNode root) {
        if(root==null) {
            return;
        }
        addRes(res,root.left);
        res.add(root.val);
        addRes(res,root.right);
    }
}

  相关解决方案