94. Binary Tree Inorder Traversal
by Botao Xiao
Thinking:
- Method:
- 中序遍历
- 左 -> 中 -> 右
/**
* 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<>();
if(root == null) return result;
inorder(root, result);
return result;
}
private static void inorder(TreeNode n, List<Integer> result){
if(n == null) return;
inorder(n.left, result);
result.add(n.val);
inorder(n.right, result);
}
}
二刷
前序,中序, 后续遍历是指父节点在两个子节点之间的位置的。这种题目必须无压力几分钟写出来。
/**
* 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 LinkedList<>();
inorderTraversal(result, root);
return result;
}
private void inorderTraversal(List<Integer> result, TreeNode root){
if(root == null) return;
inorderTraversal(result, root.left);
result.add(root.val);
inorderTraversal(result, root.right);
}
}
Subscribe via RSS