算法:中序遍历二叉树94. Binary Tree Inorder Traversal
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:中序遍历二叉树94. Binary Tree Inorder Traversal相关的知识,希望对你有一定的参考价值。
94. Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
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() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
helper(root, list);
return list;
}
private void helper(TreeNode root, List<Integer> list) {
if (root == null) return;
helper(root.left, list);
list.add(root.val);
helper(root.right, list);
}
}
遍历解法
将一个 Node 的所有左子节点都压入堆栈,这样我的想法就很清楚了:
- 我们将 root 的所有左孩子推入堆栈,直到没有更多节点。
- 然后我们从我们调用的堆栈中弹出cur。
- 添加cur到结果列表
- 设置
root = node.right
, 以此循环。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while(root != null) {
stack.add(root);
root = root.left;
}
TreeNode node = stack.pop();
list.add(node.val);
root = node.right;
}
return list;
}
}
以上是关于算法:中序遍历二叉树94. Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 94.Binary Tree Inorder Traversal 二叉树的中序遍历
LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树迭代)
94. Binary Tree Inorder Traversal(非递归实现二叉树的中序遍历)