94. 二叉树的中序遍历
作者:互联网
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
TreeNode cur = root;
while (cur != null) {
TreeNode mostRight = cur.left;
if (mostRight != null) {
while (mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
if (mostRight.right == null) {
mostRight.right = cur;
cur = cur.left;
continue;
} else {
mostRight.right = null;
}
}
ret.add(cur.val);
cur = cur.right;
}
return ret;
}
}
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;
}
}
标签:right,TreeNode,cur,val,中序,mostRight,二叉树,94,left 来源: https://www.cnblogs.com/tianyiya/p/15686607.html