LintCode(632)查詢二叉樹中值最大的節點
問題
Find the maximum node in a binary tree, return the node.
Example
Given a binary tree:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
return the node with value 3
.
考慮遍歷二叉樹來解決
java解答
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of tree
* @return: the max node
*/
/**
* 思路
* 1,引數合法性判斷
* 2,遍歷二叉樹,找出最大節點
*/
public TreeNode maxNode(TreeNode root) {
// write your code here
if(root == null){
return null;
}
//最大的節點
TreeNode maxNode = root;
//當前節點
TreeNode p = root;
//臨時存放二叉樹的連結串列集合
LinkedList<TreeNode> nodeLink = new LinkedList<TreeNode>();
while(p != null || !nodeLink.isEmpty()){
if(p != null){
nodeLink.push(p);
p = p.left;
}else{
p = nodeLink.pop();
if(maxNode.val < p.val){
maxNode = p;
}
p = p.right;
}
}
return maxNode;
}
}