回溯专题之二叉树
目录
题目链接:
思路分析(全是dfs+递归)+代码实现
二叉树的右视图
思路
代码实现
二叉树展开为链表
思路
代码
路径总和III
思路
代码
二叉树中的最大路径和
思路
代码
最近做了几道二叉树的题,都是力扣hot上面的。都是用dfs+递归的思想解决的。以前学二叉树的时候,觉得递归特别难。但是现在经过回溯的训练后,再看二叉树的递归,是觉得如此之巧妙。跟着我一起暴打力扣hot把,拿下二叉树。
题目链接:
199. 二叉树的右视图 - 力扣(LeetCode)
114. 二叉树展开为链表 - 力扣(LeetCode)
437. 路径总和 III - 力扣(LeetCode)
124. 二叉树中的最大路径和 - 力扣(LeetCode)
思路分析(全是dfs+递归)+代码实现
二叉树的右视图
思路

代码实现
class Solution {List<Integer> ret=new ArrayList<>();int max_deepth=-1;public List<Integer> rightSideView(TreeNode root) {dfs(root,0);return ret;}public void dfs(TreeNode root,int currentdeepth){if(root==null){return;}if(currentdeepth>max_deepth){ret.add(root.val);max_deepth=currentdeepth;}dfs(root.right,currentdeepth+1);dfs(root.left,currentdeepth+1);}
}
二叉树展开为链表
思路

代码
class Solution {List<Integer> ret=new ArrayList<>();public void flatten(TreeNode root) { pretravle(root);dfs(root,0);}public void pretravle(TreeNode root){if(root==null){return;}ret.add(root.val);pretravle(root.left);pretravle(root.right);}public void dfs(TreeNode root,int pos){if(pos==ret.size()){return;}root.left=null;if(pos+1<ret.size()){root.right=new TreeNode(ret.get(pos+1));dfs(root.right,pos+1);}else{root.right=null;return;}}
}
路径总和III
思路

代码
class Solution {int count=0;int targetSum=0;public int pathSum(TreeNode root, int _targetSum) {targetSum=_targetSum;travel(root);return count; }public void travel(TreeNode root){
if(root==null){return;}dfs(root,0);travel(root.left);travel(root.right);
}public void dfs(TreeNode root,long currentSum){
if(root==null){return;}currentSum+=root.val;if(targetSum==currentSum){count++;}dfs(root.left,currentSum);dfs(root.right,currentSum);}
}
二叉树中的最大路径和
思路


代码
class Solution {int max=-0x3f3f3f3f;public int maxPathSum(TreeNode root) {//每次进来重置maxmax=-0x3f3f3f3f;dfs(root);return max; }public int dfs(TreeNode root){if(root==null){return 0;}//如果左子树的和为负数 就直接不选int leftSum=Math.max(0,dfs(root.left));int rightSum=Math.max(0,dfs(root.right));int currentSum=root.val+leftSum+rightSum;max=Math.max(currentSum,max);return root.val+Math.max(leftSum,rightSum);}}
