网易有道笔试:
求一个二叉树中任意两个节点间的最大距离,
两个节点的距离的定义是这两个节点间边的个数,
比如某个孩子节点和父节点间的距离是1,
和相邻兄弟节点间的距离是2,
优化时间空间复杂度。
思路:
用l_depth和r_depth保存左子树最大高度和右子树最大高度。
res保存以该节点为根节点时的的最大距离,不断向上更新。
class TreeNode {
int l_depth;
int r_depth;
int res;
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class m23_maxDisTree {
public static void main(String[] args) {
int max=0;
TreeNode root = new TreeNode(2);
root.left=new TreeNode(3);
root.left.left=new TreeNode(3);
root.left.left.left=new TreeNode(3);
root.left.right=new TreeNode(1);
root.left.right.right=new TreeNode(1);
System.out.println(maxDis(root));
}
public static int maxDis(TreeNode root) {
Depth(root);
return root.res;
}
public static int Depth(TreeNode root) {
if(root==null) {
return 0;
}
if(root.left!=null) {
root.l_depth=Depth(root.left); // 左子树最大高度
root.res=Math.max(root.res,root.left.res); // 更新最大距离
}
if(root.right!=null) {
root.r_depth=Depth(root.right); // 右子树最大高度
root.res=Math.max(root.res,root.right.res); // 更新最大距离
}
int sum=root.l_depth+root.r_depth; // 当路径经过该节点时的距离
root.res=Math.max(root.res, sum); // 更新最大距离
return Math.max(root.l_depth,root.r_depth)+1; //返回该节点高度
}
}