您的位置:首页 > 理论基础 > 数据结构算法

数据结构每日学习 Day1 二叉树

2022-01-02 22:47 1006 查看

第一题:

114. 二叉树展开为链表

解题:
首先回顾一下 二叉树的递归遍历和迭代遍历

递归遍历如下:
(三种遍历方式只需调整add语句位置即可)

public void dfs(TreeNode root,List<TreeNode> list){
if (root!=null){
list.add(root);
dfs(root.left,list);
dfs(root.right,list);
}

}

迭代遍历+Morris解法如下:

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/leetcodesuan-fa-xiu-lian-dong-hua-yan-shi-xbian-2/
中序迭代(自认为好理解的):

public static void inOrderIteration(TreeNode head) {
if (head == null) {
return;
}
TreeNode cur = head;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.pop();
System.out.print(node.value + " ");
if (node.right != null) {
cur = node.right;
}
}
}

前序迭代:(这个画个图 理解一下就很快)

public static void preOrderIteration(TreeNode head) {
if (head == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.value + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}

感觉下面这个更好理解一些

Deque<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
list.add(node);
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}

AC:

package 二叉树;

import java.util.ArrayList;
import java.util.List;

public class 二叉树展开为链表 {
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;
}
}

/*
Queue<TreeNode> queue = new ArrayDeque<>();
preOrder(root, queue);
while (!queue.isEmpty()){
TreeNode curr = queue.poll();
curr.left = null;
curr.right = queue.peek();
}
}
*/
public void flatten(TreeNode root) {
List<TreeNode> list=new ArrayList<TreeNode>();
dfs(root,list);
int len=list.size();

for (int i = 1; i <len ; i++) {
//原本下面这一行错了 注意理解
TreeNode prev = list.get(i - 1), curr = list.get(i);
prev.left=null;
prev.right=curr;

}

}
public void dfs(TreeNode root,List<TreeNode> list){
if (root!=null){
list.add(root);
dfs(root.left,list);
dfs(root.right,list);
}

}
}

第二题:543. 二叉树的直径


AC:(太妙了 首先你要会深度是怎么求的 !!! )(这个递归过程建议反复咀嚼)

class Solution {
int ans;
public int diameterOfBinaryTree(TreeNode root) {
ans = 1;
depth(root);
return ans - 1;
}
public int depth(TreeNode node) {
if (node == null) {
return 0; // 访问到空节点了,返回0
}
int L = depth(node.left); // 左儿子为根的子树的深度
int R = depth(node.right); // 右儿子为根的子树的深度
ans = Math.max(ans, L+R+1); // 计算d_node即L+R+1 并更新ans
return Math.max(L, R) + 1; // 返回该节点为根的子树的深度
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: