不能直接设个global list 去存那个path 以及current 最大值么?遍历完了树,不管 怎么遍历的。更新最大值的时候,更新对应的path就可以了?我感觉自己simple minded了。
i*n
18 楼
屠夫还真和淘金的有一拼
l*s
19 楼
A recursive solution. Returning the max value while building the List bigPath. private int printBigNodePath(TreeNode root, List bigPath) { if (root == null) return int.MinValue; bigPath.Add(root); List curLeftPath = new List(); List curRightPath = new List(); int leftBig = printBigNodePath(root.Left, curLeftPath); int rightBig = printBigNodePath(root.Right, curRightPath); if (leftBig > rightBig && leftBig > root.Value) { bigPath.AddRange(curLeftPath); return leftBig; } if (rightBig > leftBig && rightBig > root.Value) { bigPath.AddRange(curRightPath); return rightBig; } return root.Value; }
这个题需要用一个trick去记住当前相对与root的位置。 int max = int.MinValue, maxPos = 0; Inorder(Node node, int pos) { if(node == null) return; Inorder(node.left, pos*2); if(max < node.val) { max = node.val; maxPos = pos; } Inorder(node.left, pos*2+1); } Now we get max and the maxPos associated with it. Then divide the maxPos by 2 all the way to 0, for example, maxPos = 25, we get 1r->r->l-l save the array 1,3, 6, 12 and start from 1 and build up the path.
public List getMaxNodePath(TreeNode node){ List max = new ArrayList(); max.add(node.val); List res = new ArrayList(); res.add(""); findMaxPath(node, max, "", res); return res; }
【在 l******s 的大作中提到】 : A recursive solution. Returning the max value while building the List : bigPath. : private int printBigNodePath(TreeNode root, List bigPath) : { : if (root == null) return int.MinValue; : bigPath.Add(root); : List curLeftPath = new List(); : List curRightPath = new List(); : int leftBig = printBigNodePath(root.Left, curLeftPath); : int rightBig = printBigNodePath(root.Right, curRightPath);