题目:
树节点的结构为:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
求每个节点的高度,并保存在节点的val中
代码:
public int height(TreeNode root) {
if(root == null) {
return 0;
}
root.val = Math.max(height(root.left), height(root.right)) + 1;
return root.val;
}