“二叉树的中序遍历”的版本间的差异

来自qingwei personal wiki
跳转至: 导航搜索
第55行: 第55行:
 
}
 
}
 
</source>
 
</source>
 +
 +
[[category: 算法]]
 +
[[category: leetcode]]
 +
[[category: 树]]

2018年5月28日 (一) 14:40的版本

中序

中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树

相对于根来说,
* 中序指 根 中间次序访问
* 先序指 根 首先访问
* 后续指 根 最后访问

描述

leetcode

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
https://leetcode.com/problems/binary-tree-inorder-traversal/description/

问题

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

递归

/**
 * 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> result = new ArrayList<>();
        inorder(root, result);
        return result;
    }
    
    private void inorder(TreeNode root, List<Integer> res) {
        if(root != null) {
            inorder(root.left, res);
            res.add(root.val);
            inorder(root.right, res);
        }
    }
}