在二叉树中寻找值最大的节点并返回——LintCode入门

样例

给出如下一棵二叉树:

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

返回值为 3 的节点。

示例代码:

public class Solution {
/**
* @param root the root of binary tree
* @return the max ndoe
*/
  public TreeNode maxNode(TreeNode root) {
  // Write your code here
  if(root == null) return null;
  TreeNode left = root;
  TreeNode right = root;
  if(root.left !=null) left=maxNode(root.left);
  if(root.right !=null) right =maxNode(root.right);
  if(left.val > root.val) root.val = left.val;
  if(right.val > root.val) root.val = right.val;
  return root;
  }
}

posted @ 2017-05-10 09:21  JTAY  阅读(1025)  评论(0编辑  收藏  举报