二叉树的各种算法面试题及答案解析

前言

下面的所有面试题及解析答案都是经过验证的。

面试题

树的定义
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
计算树的结点数量(递归)

树的结点数量等于左子树加上右字数的数量+1

public class Solution {
    public int sumOfNode(TreeNode root) {
        if(root==null){
            return 0;
        }
         int leftSum=sumOfNode(root.left);
         int rightSum=sumOfNode(root.right);
         return leftSum+rightSum+1;
    }
}
计算树的结点数量(非递归)

使用队列,取出上层结点的同时,将下层左右子节点存入

public class Solution {
    public int sumOfNode(TreeNode root) {
        if(root==null){
            return 0;
        }
         Queue<TreeNode> queue=new LinkedList<TreeNode>();
         queue.offer(root);
         int sum=0while(!queue.isEmpty()){
			TreeNode node=queue.poll();
			sum++;
			if(node.left!=null){
				queue.offer(node.left);
			}
			if(node.right!=null){
				queue.offer(node.right);
			}
		}
         return sum;
    }
}
树的深度计算(非递归)
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        int currentLevelNodes=1;     //记录当前层的结点数量
        int nextLevelNodes=0;          //记录下一层结点的数量
        int depth=0;                  //记录树的深度
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.poll();        //取出一个结点,记录该结点的下一层结点,这也是queue的使用原因
            currentLevelNodes--;
            if(node.left!=null){
                queue.offer(node.left);
                nextLevelNodes++;
            }
            if(node.right!=null){
                queue.offer(node.right);
                nextLevelNodes++;
            }
            if(currentLevelNodes==0){
                currentLevelNodes=nextLevelNodes;
                nextLevelNodes=0;
                depth++;
            }
            
        }
        return depth;
    }
}
树的深度计算(递归)
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        int leftLength=TreeDepth(root.left);
        int rightLength=TreeDepth(root.right);
        return Math.max(leftLength,rightLength)+1;
    }
}
从上向下遍历树

记得使用队列 Queue!!

import java.util.Queue;
import java.util.LinkedList;
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null){
            return array;
        }
         Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.poll();
            if(node.left!=null){
                queue.offer(node.left);
            }
            if(node.right!=null){
                queue.offer(node.right);
            }
            array.add(node.val);
        }
        return array;
    }
}
前序遍历(递归)

这里的陷阱在于ArrayList<Integer> array=new ArrayList<Integer>();变量array的使用

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null){
            return array;
        }
        preorderTraversal(root,array);
        return array;
    }
    public void preorderTraversal(TreeNode root,ArrayList<Integer> array){
        if(root==null){
            return;
        }
        array.add(root.val);
        preorderTraversal(root.left,array);
        preorderTraversal(root.right,array);
    }
}
前序遍历(非递归)

使用栈,对于每一个结点来说,先将它的右节点放进去,再将左节点放进去,然后循环拿出栈顶元素,这样可以做到执行完所有的左子树才能轮上右子树。

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null){
            return array;
        }
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node=stack.pop();
            array.add(node.val);
            if(node.right!=null){
                stack.push(node.right);
            }
            if(node.left!=null){
                stack.push(node.left);
            }
        }
        return array;
    }
}
中序遍历(递归)

这里的陷阱在于ArrayList<Integer> array=new ArrayList<Integer>();变量array的使用

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null){
            return array;
        }
        inorderTraversal(root,array);
        return array;
    }
    public void inorderTraversal(TreeNode root,ArrayList<Integer> array){
        if(root==null){
            return;
        }
        inorderTraversal(root.left,array);
        array.add(root.val);
        inorderTraversal(root.right,array);
    }
}
后序遍历(递归)
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null){
            return array;
        }
        postorderTraversal(root,array);
        return array;
    }
    public void postorderTraversal(TreeNode root,ArrayList<Integer> array){
        if(root==null){
            return;
        }
        postorderTraversal(root.left,array);
        postorderTraversal(root.right,array);
        array.add(root.val);
    }
}
二叉树中和为某一值的路径(递归)
public class Solution {
    ArrayList<ArrayList<Integer>> array=new  ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> temp=new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root==null){
            return array;
        }
        temp.add(root.val);
        target-=root.val;
        if(target==0&&root.left==null&&root.right==null){
            array.add(new ArrayList(temp));                   //创建新的ArrayList
        }
        FindPath(root.left,target);
        FindPath(root.right,target);
        temp.remove(temp.size()-1);                            //深度优先算法回退一步
        return array;
    }
}
leetCode:sum-root-to-leaf-numbers

题目表述:

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,
    1
   / \
  2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.
public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return root.val;
        }
        int sum=0;
        return sumNumbers(root,sum);
    }
    public int sumNumbers(TreeNode root,int sum){
        if(root==null){
            return 0;
        }
        sum=10*sum+root.val;
        if(root.left==null&&root.right==null){        //必须加这个,不然返回都是0
            return sum;
        }
        int sumLeft=sumNumbers(root.left,sum);
        int sumRight=sumNumbers(root.right,sum);
        return sumLeft+sumRight;
    }
}
引荐好文章

1.二叉树面试题总结

2.二叉树面试题leetCode总结

  • 2
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值