leetcode练习
二叉树前序非递归
前序遍历,根节点入栈,栈不为空,栈首出栈,节点右孩子进栈,节点左孩子进栈。
// 前序遍历顺序:中-左-右,入栈顺序:中-右-左
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null){
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
return result;
}
二叉树中序非递归
根节点进栈,左子树不空,进栈,直到左子树为空,移出栈首元素,遍历栈首元素右子树
// 中序遍历顺序: 左-中-右 入栈顺序: 左-右
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null){
return result;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()){
if (cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
二叉树后序非递归
和前序非递归相似,只不过先入左节点,再入右节点,最后将结果逆序。
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null){
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if (node.left != null){
stack.push(node.left);
}
if (node.right != null){
stack.push(node.right);
}
}
Collections.reverse(result);
return result;
}
二叉树Morris遍历
public void morris(TreeNode head) {
if (head == null) {
return;
}
TreeNode cur = head;
TreeNode mostRight = null;
while (cur != null) {
mostRight = cur.left; //mostRight是左孩子
if (mostRight != null) { // 有左孩子
while (mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
// mostRight变成了cur左子树上,最右的节点
if (mostRight.right == null) { // 这是第一次来到cur
mostRight.right = cur;
cur = cur.right;
continue;
} else { // mostRight.right == cur
mostRight.right = null;
}
}
cur = cur.right;
}
}
morris前序遍历
public void morris(TreeNode head) {
if (head == null) {
return;
}
TreeNode cur = head;
TreeNode mostRight = null;
while (cur != null) {
mostRight = cur.left;
if (mostRight != null) {
while (mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
if (mostRight.right == null) {
System.out.println(cur.value);
mostRight.right = cur;
cur = cur.right;
continue;
} else {
mostRight.right = null;
}
} else {
System.out.println(cur.value);
}
cur = cur.right;
}
}
morris中序遍历
public void morrisIn(TreeNode head) {
if (head == null) {
return;
}
TreeNode cur = head;
TreeNode mostRight = null;
while (cur != null) {
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.right;
continue;
} else {
mostRight.right = null;
}
}
System.out.println(cur.value);
cur = cur.right;
}
}
morris后序太复杂,不做记录