JZ55 二叉树的深度 ⭐
直接上代码
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
else {
return 1+Math.max(TreeDepth(root.left),TreeDepth(root.right));
}
}
}
JZ77 按之字形顺序打印二叉树 ⭐⭐
思路1
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
depth(pRoot,1,res);
for (int i = 1; i < res.size(); i+=2) {
Collections.reverse(res.get(i));
}
return res;
}
private void depth(TreeNode root,int d,ArrayList<ArrayList<Integer>> list){
if(root==null) return;
if(d>list.size()){
list.add(new ArrayList<Integer>());
}
list.get(d-1).add(root.val);
depth(root.left,d+1,list);
depth(root.right,d+1,list);
}
}
思路2
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
LinkedList<TreeNode> qu = new LinkedList<>();
if (pRoot != null) {
qu.offer(pRoot);
}
int row = 1;
while (!qu.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = qu.size(); i > 0; i--) {
TreeNode t = qu.removeFirst(); //头出
list.add(t.val);
if (t.left != null) { //尾入
qu.addLast(t.left);
}
if (t.right != null) {
qu.addLast(t.right);
}
}
if (row % 2 == 0) {
Collections.reverse(list);
ans.add(list);
} else {
ans.add(list);
}
row++;
}
return ans;
}
}
JZ54 二叉搜索树的第k个节点 ⭐⭐
public class Solution {
ArrayList<Integer> ans = new ArrayList<>();
public int KthNode (TreeNode proot, int k) {
if (proot == null || k == 0) return -1;
inorder(proot);
Collections.sort(ans);
return ans.size() >= k ? ans.get(k - 1) : -1;
}
public void inorder(TreeNode proot) {
if (proot != null) {
inorder(proot.left);
ans.add(proot.val);
inorder(proot.right);
}
}
}