您的位置:首页 > 其它

LintCode之632 二叉树最大节点

2017-11-22 22:41 435 查看
题目来源:二叉树最大节点

题目描述:

在二叉树中寻找值最大的节点并返回。

样例:

给出如下一棵二叉树:

1
/   \
-5    2
/  \ /  \
0  3 -4 -5


返回值为 3 的节点。

Java代码:

public TreeNode maxNode(TreeNode root) {
// Write your code here
TreeNode result = null;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.empty()){
while (root != null) {
if (result==null||result.val < root.val) {
result = root;
}
stack.push(root);
root = root.left;
}
if(!stack.empty()){
root = stack.lastElement();
stack.pop();
if (result==null||result.val < root.val) {
result = root;
}
root = root.right;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: