给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
public class Solution {
public int FindBottomLeftValue(TreeNode root) {
int ret = 0;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while(queue.Count > 0)
{
TreeNode p = queue.Dequeue();
if(p.right != null)
{
queue.Enqueue(p.right);
}
if (p.left != null)
{
queue.Enqueue(p.left);
}
ret = p.val;
}
return ret;
}
}
public class Solution {
int curVal = 0;
int curHeight = 0;
public int FindBottomLeftValue(TreeNode root) {
int curHeight = 0;
DFS(root, 0);
return curVal;
}
public void DFS(TreeNode root, int height) {
if (root == null) {
return;
}
height++;
DFS(root.left, height);
DFS(root.right, height);
if (height > curHeight) {
curHeight = height;
curVal = root.val;
}
}
}