编程之美--3.8 求二叉树中节点的最大距离

本文介绍了两种求解二叉树中最长路径的算法实现,一种是递归方法,另一种是迭代方法。递归方法通过修改节点记录左右子树的最大深度来解决;迭代方法采用后序遍历的方式,并巧妙地利用栈进行节点处理。
思路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;
			
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值