思路1
递归。需要改变TreeNode的类型,能够记录自己左右的最大深度。
代码1
public static void FindMaxLenRec(MyTreeNode root){
if(root == null){
return ;
}
if(root.left == null){
root.nMaxLeft =0;
}
if(root.right ==null){
root.nMaxRight = 0;
}
if(root.left!=null){
FindMaxLenRec(root.left);
}
if(root.right!=null){
FindMaxLenRec(root.right);
}
if(root.left!=null){
int nTempMax =0;
if(root.left.nMaxLeft>root.left.nMaxRight){
nTempMax = root.left.nMaxLeft;
}
else{
nTempMax = root.left.nMaxRight;
}
root.nMaxLeft = nTempMax+1;
}
if(root.right!=null){
int nTempMax =0;
if(root.right.nMaxLeft>root.right.nMaxRight){
nTempMax = root.right.nMaxLeft;
}
else{
nTempMax = root.right.nMaxRight;
}
root.nMaxRight = nTempMax+1;
}
if(root.nMaxLeft+root.nMaxRight>nMaxValue){
nMaxValue =root.nMaxLeft+root.nMaxRight;
}
}
思路2
迭代。可以想到用后序来做。难点:1 后序的迭代写法(不用双栈的写法) 2 什么时候统计左右子树最大深度。
代码2
public static void FindMaxLenIte(MyTreeNode root){
MyTreeNode pre = root;
MyTreeNode cur = root;
LinkedList<MyTreeNode> stack = new LinkedList<MyTreeNode>();
while(cur!=null){
while(cur.left!=null){
stack.push(cur);
cur = cur.left;
}
while(cur.right==null || cur.right == pre){
if(cur.right == pre){
cur.nMaxRight = pre.Max+1;
}
if(cur.left == pre){
cur.nMaxLeft = pre.Max+1;
}
cur.Max=Math.max(cur.nMaxLeft, cur.nMaxRight);
if(nMaxValue<(cur.nMaxLeft+cur.nMaxRight)){
nMaxValue = cur.nMaxLeft+cur.nMaxRight;
}
pre = cur;
if(stack.isEmpty()){
return;
}
cur = stack.pop();
}
if(pre == cur.left){
cur.nMaxLeft= pre.Max+1;
}
stack.push(cur);
cur = cur.right;
}
}
本文介绍了两种求解二叉树中最长路径的算法实现,一种是递归方法,另一种是迭代方法。递归方法通过修改节点记录左右子树的最大深度来解决;迭代方法采用后序遍历的方式,并巧妙地利用栈进行节点处理。
2010

被折叠的 条评论
为什么被折叠?



