算法专题十二:二叉树的深搜
计算布尔二叉树的值
2331. 计算布尔二叉树的值 - 力扣(LeetCode)
class Solution {public boolean evaluateTree(TreeNode root) {if(root.left==null || root.right==null){return root.val==0?false:true;}boolean left=evaluateTree(root.left);boolean right=evaluateTree(root.right);return root.val==2?left|right:left&right;}
}
求根节点到叶节点的数字之和
129. 求根节点到叶节点数字之和 - 力扣(LeetCode)
class Solution {public int sumNumbers(TreeNode root) {return dfs(root,0);}public int dfs(TreeNode root,int sum) {sum=sum*10+root.val;if(root.left==null && root.right==null){return sum;}int ret=0;if(root.left!=null){ret+=dfs(root.left,sum);}if(root.right!=null){ret+=dfs(root.right,sum);}return ret;}
}
二叉树剪枝
814. 二叉树剪枝 - 力扣(LeetCode)
class Solution {public TreeNode pruneTree(TreeNode root) {if(root==null){return null;}root.left=pruneTree(root.left);root.right=pruneTree(root.right);if(root.left==null && root.right==null && root.val==0){return null;}return root;}
}
验证二叉搜索树
98. 验证二叉搜索树 - 力扣(LeetCode)
/*** Definition for a binary tree node.* 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;* }* }*/
class Solution {long prev=Long.MIN_VALUE;public boolean isValidBST(TreeNode root) {if(root==null){return true;}boolean left=isValidBST(root.left);//剪枝操作if(left==false){return false;}boolean cur=false;if(root.val>prev){cur= true;}//剪枝操作if(cur==false){return false;}prev=root.val;boolean right=isValidBST(root.right);if(root.val>prev){cur= true;}return cur && left && right ;}
}
二叉搜索树中第K小的元素
class Solution {int count;int ret;public int kthSmallest(TreeNode root, int k) {count=k;dfs(root);return ret;}public void dfs(TreeNode root){if(root==null ||count ==0){return ;}dfs(root.left);count--;if(count==0){ret=root.val;}if(count==0){return ;}dfs(root.right);}
}
二叉树的所有路径
257. 二叉树的所有路径 - 力扣(LeetCode)
class Solution {List<String> ret;public List<String> binaryTreePaths(TreeNode root) {ret=new ArrayList();dfs(root,new StringBuffer());return ret;}public void dfs(TreeNode root,StringBuffer path1){StringBuffer path=new StringBuffer(path1);if(root==null){return ;}path.append(Integer.toString(root.val));if(root.left==null && root.right==null){ret.add(path.toString());}path.append("->");if(root.left!=null){dfs(root.left,path);}if(root.right!=null){dfs(root.right,path);}}
}