赞
踩
题目链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/description/?envType=study-plan-v2&envId=top-100-liked
思路:最简单的中序遍历,无需多说。
class Solution { List<Integer> list = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { order(root); return list; } void order(TreeNode root) { if(root == null) { return ; } order(root.left); list.add(root.val); order(root.right); } }
题目链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:后续遍历到根节点,选取左右子树的结果中的最大值作为子树深度,然后加1即本节点,返回。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
题目链接:https://leetcode.cn/problems/invert-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:前序遍历,然后逐个交换节点左右子树即可。
class Solution { public TreeNode invertTree(TreeNode root) { order(root); return root; } void order(TreeNode root) { if(root == null) return ; TreeNode t = root.left; root.left = root.right; root.right = t; order(root.left); order(root.right); } }
题目链接:https://leetcode.cn/problems/symmetric-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:判断是否是对称二叉树,直接把根节点的左右子树,作为一颗树进行遍历。
class Solution {
public boolean isSymmetric(TreeNode root) {
return isEquels(root.left, root.right);
}
boolean isEquels(TreeNode child1, TreeNode child2) {
if(child1 == null && child2 == null) return true;
if((child1 == null && child2 != null) || (child1 != null && child2 == null)) return false;
if(child1.val != child2.val) return false;
return isEquels(child1.left, child2.right) && isEquels(child1.right, child2.left);
}
}
题目链接:https://leetcode.cn/problems/diameter-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:其实求的就是任意一个节点其左右子树能够连接的最长边长,那么问题就转化为求每个节点左子树的最长路径和右子树的最长路径和。
class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { order(root); return max; } int order(TreeNode root) { if(root == null) return 0; int left = order(root.left); int right = order(root.right); max = Math.max(max, left + right); return Math.max(left, right) + 1; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。