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]
Solution:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) {
return list;
}
if(root.left != null) {
inorderTraversal(root.left);
}
if(root != null) {
list.add(root.val);
}
if(root.right != null) {
inorderTraversal(root.right);
}
return list;
}
}
本文介绍了一种解决二叉树中序遍历问题的方法,通过递归算法实现节点值的有序收集,最终返回一个包含所有节点值的有序列表。
736

被折叠的 条评论
为什么被折叠?



