110
题目:
给定一个二叉树,判断它是否是 平衡二叉树
题目链接:110. 平衡二叉树 - 力扣(LeetCode)
思路:
第一种,使用递归
第二种,使用迭代法(没看懂)
代码:
//递归
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return getDepth(root)!=-1;
}
public int getDepth(TreeNode root)
{
if(root==null) return 0;
int left =getDepth(root.left);
if(left==-1) return-1;
int right =getDepth(root.right);
if (right==-1) return -1;
if (Math.abs(left - right) > 1)
return -1;
return 1+Math.max(getDepth(root.left),getDepth(root.right));
}
257
题目:
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
题目链接:257. 二叉树的所有路径 - 力扣(LeetCode)
思路:
第一种,使用递归+回溯
第二种,使用迭代法,先序遍历使用一个栈,每次同时压入结点和记录。
代码:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<Integer> path =new ArrayList<Integer>();
List<String>res =new ArrayList<String>();
if(root==null) return res;
traversal(root,path,res);
return res;
}
public void traversal(TreeNode root,List<Integer>path,List<String>res)
{
path.add(root.val);
if(root.left==null&&root.right==null)
{
StringBuilder sb =new StringBuilder();
for(int i=0;i<path.size()-1;i++)
sb.append(path.get(i)).append("->");
sb.append(path.get(path.size()-1));
res.add(sb.toString());
return;
}
if(root.left!=null)
{
traversal(root.left,path,res);
path.remove(path.size()-1);//回溯,返回上一层结点
}
if(root.right!=null)
{
traversal(root.right,path,res);
path.remove(path.size()-1);//回溯,返回上一层结点
}
}
}
404
题目:
给定二叉树的根节点 root
,返回所有左叶子之和。
题目链接:404. 左叶子之和 - 力扣(LeetCode)
思路:
注意如何判断一个结点是不是左叶子结点
第一种,使用递归
第二种,迭代法,任何一个遍历+判断该结点的左结点是不是左叶子结点
代码:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return leftsum(root);
}
public int leftsum(TreeNode root)
{
if(root==null) return 0;
if(root.left==null && root.right==null) return 0;
int left=0;
int right=0;
//左叶子结点
if(root.left!=null&& root.left.left == null && root.left.right == null)
left = root.left.val;
else //非叶子结点的左子树
left = leftsum(root.left);
right = leftsum(root.right);
return left+right;
}
}