“二叉树的中序遍历”的版本间的差异
来自qingwei personal wiki
(→迭代) |
|||
(未显示同一用户的3个中间版本) | |||
第55行: | 第55行: | ||
} | } | ||
</source> | </source> | ||
+ | == 迭代 == | ||
+ | <source lang="java"> | ||
+ | /** | ||
+ | * 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<>(); | ||
+ | |||
+ | Stack<TreeNode> stack = new Stack<>(); | ||
+ | TreeNode cur = root; | ||
+ | |||
+ | while(cur != null || !stack.empty()) { | ||
+ | while(cur != null) { | ||
+ | // 栈里保存的是 非叶节点 | ||
+ | stack.push(cur); | ||
+ | cur = cur.left; | ||
+ | } | ||
+ | |||
+ | cur = stack.pop(); | ||
+ | result.add(cur.val); | ||
+ | cur = cur.right; | ||
+ | } | ||
+ | |||
+ | return result; | ||
+ | } | ||
+ | } | ||
+ | </source> | ||
+ | [[category: 算法]] | ||
+ | [[category: leetcode]] | ||
+ | [[category: 树]] |
2018年6月3日 (日) 09:16的最新版本
中序
中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树 相对于根来说, * 中序指 根 中间次序访问 * 先序指 根 首先访问 * 后续指 根 最后访问
描述
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);
}
}
}
迭代
/**
* 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<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || !stack.empty()) {
while(cur != null) {
// 栈里保存的是 非叶节点
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
return result;
}
}