目录
1、222.完全二叉树的节点个数
方法一:遍历获得总节点数
方法二:利用完全二叉树的性质(左子树深度==右子树深度)
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int ldepth = 1, rdepth = 1;
TreeNode left = root.left;
TreeNode right = root.right;
while(left != null)
{
++ldepth;
left = left.left;
}
while(right != null)
{
++rdepth;
right = right.right;
}
if(ldepth == rdepth) return (1 << ldepth) - 1;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
2、110.平衡二叉树
递归
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode root)
{
if(root == null) return 0;
int lheight = getHeight(root.left);
if(lheight == -1) return -1;
int rheight = getHeight(root.right);
if(rheight == -1) return -1;
if(Math.abs(lheight - rheight) > 1) return -1;
return Math.max(lheight,rheight) + 1;
}
}
3、257. 二叉树的所有路径
递归+回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
if (root == null)
return new ArrayList<String>();
List<String> res = new ArrayList<>();
List<Integer> pathList = new ArrayList<>();
getPath(root,pathList,res);
return res;
}
public void getPath(TreeNode root,List<Integer> pathList,List<String> res)
{
pathList.add(root.val);
if(root.left == null && root.right == null)
{
StringBuffer tmp = new StringBuffer();
for(int i = 0; i < pathList.size() - 1; ++i)
{
tmp.append(pathList.get(i) + "->");
}
tmp.append(pathList.get(pathList.size() - 1));
res.add(tmp.toString());
return;
}
if(root.left != null)
{
getPath(root.left,pathList,res);
pathList.remove(pathList.size() - 1);
}
if(root.right != null)
{
getPath(root.right,pathList,res);
pathList.remove(pathList.size() - 1);
}
}
}
4、404.左叶子之和
easy递归
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
int res = 0;
if(root.left != null)
{
if(root.left.left == null && root.left.right == null)
res += root.left.val;
else
res += sumOfLeftLeaves(root.left);
}
if(root.right != null)
{
if(root.right.left != null || root.right.right != null)
res += sumOfLeftLeaves(root.right);
}
return res;
}
}